Скачивая файл, и я получаю заголовок Content-Length недействителен - PullRequest
0 голосов
/ 02 марта 2010

Я загружаю файл с веб-сервера, используя приведенный ниже код, и получаю эту ошибку:

Ошибка: Ошибка сохранения файла с URL: сервер совершил нарушение протокола.

Section = ResponseHeader Detail = Недопустимое значение заголовка 'Content-Length'

При запуске Fiddler во время его работы он говорит:

Заголовок ответа Content-Length не является допустимым целым числом без знака Длина контента: 13312583

Код:

public static bool SaveFileFromURL(string url, string destinationFileName, int timeoutInSeconds)
        {
            //SetAllowUnsafeHeaderParsing20();
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            SettingsSection section = (SettingsSection)config.GetSection("system.net/settings");
            section.HttpWebRequest.UseUnsafeHeaderParsing = false;
            config.Save();

            // Create a web request to the URL
            HttpWebRequest MyRequest = (HttpWebRequest)WebRequest.Create(url);
            MyRequest.UseDefaultCredentials = true;
            MyRequest.ContentLength = 0;

            MyRequest.Timeout = timeoutInSeconds * 1000;
            try
            {
                // Get the web response
                HttpWebResponse MyResponse = (HttpWebResponse)MyRequest.GetResponse();

                // Make sure the response is valid
                if (HttpStatusCode.OK == MyResponse.StatusCode)
                {
                    // Open the response stream
                    using (Stream MyResponseStream = MyResponse.GetResponseStream())
                    {
                        // Open the destination file
                        using (FileStream MyFileStream = new FileStream(destinationFileName, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            // Create a 4K buffer to chunk the file
                            byte[] MyBuffer = new byte[4096];
                            int BytesRead;
                            // Read the chunk of the web response into the buffer
                            while (0 < (BytesRead = MyResponseStream.Read(MyBuffer, 0, MyBuffer.Length)))
                            {
                                // Write the chunk from the buffer to the file
                                MyFileStream.Write(MyBuffer, 0, BytesRead);
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                throw new Exception("Error saving file from URL:" + err.Message, err);
            }
            return true;
        }

Обновление : если я передаю URL-адрес прямо в браузер, файл успешно загружается, и в строке GetResponse выдается ошибка.

Обновление 2 : я получаю ту же ошибку с WebClient.Downloadfile:

public static bool DL_Webclient(string url, string destinationFileName)
{
    WebClient myWebClient = new WebClient();
    myWebClient.UseDefaultCredentials = true;
    myWebClient.DownloadFile(url, destinationFileName);

    return true;
}

Обновление 3 : получив другие заголовки в сообщении (используя Fiddler), они:

HTTP/1.1 200 OK
Connection: close
Date: Wed, 03 Mar 2010 08:43:06 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Content-Length: 13314320
Content-Type: application/x-evsaveset
Set-Cookie: ASPSESSIONIDQQCQSCRC=CFHHJHADOIBCFAFOHFJCDNEG; path=/
Cache-control: private

Ответы [ 2 ]

0 голосов
/ 03 марта 2010

Не могли бы вы вместо этого использовать WebClient.DownloadFile ?

0 голосов
/ 02 марта 2010

Есть ли другие HTTP-заголовки?

Возможно, это связано с заголовком «Transfer-Encoding» или аналогичными правилами. Более подробную информацию об этих заголовках и их влиянии на заголовок Content-Length можно найти на сайтах W3C и Подробнее на сайте W3C

Надеюсь, это поможет,

...