Search code examples
c#.nethttphttpwebrequesthttpwebresponse

Content length is always negative


I don't know but content length is always negative even if repsonse has corrent Content-Length header. For example:

class Program
{
    static void Main()
    {
        try
        {
            string result = Get("http://stackoverflow.com/");
            Console.WriteLine("Response length = {0}", result.Length);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }

    static string Get(string adr)
    {
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(adr);
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0";
        req.Proxy = null;
        req.KeepAlive = false;
        req.Headers.Add("Accept-Language", "ru-RU,ru;q=0.9,en;q=0.8");
        req.AllowAutoRedirect = true;
        req.Timeout = 10000;
        req.ReadWriteTimeout = 10000;
        req.MaximumAutomaticRedirections = 10;
        req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        req.Method = WebRequestMethods.Http.Get;


        using (var response = (HttpWebResponse) req.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                if (stream == null)
                    throw new NullReferenceException("Response stream is nulL!");
                using (var reader = new StreamReader(stream, Encoding.Default))
                {
                    Console.WriteLine("Content length = {0}", response.ContentLength);
                    return WebUtility.HtmlDecode(reader.ReadToEnd());
                }
            }
        }
    }
}

fiddler shows following output:

HTTP/1.1 200 OK
Date: Wed, 02 Sep 2015 20:36:42 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Cache-Control: private, max-age=0
Cf-Railgun: fe8c0e42fd 44.42 0.042796 0030 3350
X-Frame-Options: SAMEORIGIN
X-Request-Guid: bc3ccb1f-1de5-4375-b30d-f3c89134cf86
Server: cloudflare-nginx
CF-RAY: 21fc0233f6652bca-AMS
Content-Length: 251540

But in program I get this:

enter image description here

how can it be fixed?


Solution

  • A couple of things:

    When I try, stackoverflow.com does not set a Content-Length header, so it will come through as -1.

    But, changing the URL to use a server which definitely does set a Content-Length header, e.g., www.theguardian.com, still produces the same result: -1.

    I think it's your use of AutomaticDecompression on the HttpWebRequest object.

    If you don't set that property the ContentLength property comes through correctly.