Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Don't (blindly) trust in HttpWebResponse.ContentLength

0.00/5 (No votes)
5 Jan 2013 1  
Don't (blindly) trust in HttpWebResponse.ContentLength.
Happy new year to all of you, it's been a long time since I have not posted on my blog.

While doing some HTTP web requests few days ago,I remained stuck with a strange HttpWebResponse.ContentLength == -1 issue with chunked data beyond a certain length.

My searches on the Web didn't give me a clear solution (or I didn't find / see it), so after some tests with Fiddler2, I think I was able to infer an explication, although I can't say I have the answer.

Here is one of the HTTP reponses with a correct Content-Length:
HTTP/1.1 200 OK
Date: Tue, 01 Jan 2013 21:48:42 GMT
Server: Apache
Content-Disposition: attachment; filename="*****.***"
Content-Length: 1537
Content-Type: application/***
Content-Language: fr-FR
Via: 1.1 ***.**********.**
X-Cache: MISS from ***.**********.**
Keep-Alive: timeout=15, max=90
Connection: Keep-Alive
And one with a "corrupted" Content-Length :
HTTP/1.1 200 OK
Date: Tue, 01 Jan 2013 21:48:44 GMT
Server: Apache
Content-Disposition: attachment; filename="*****.***"
Content-Type: application/***
Content-Language: fr-FR
Via: 1.1 ***.**********.**
X-Cache: MISS from ***.**********.**
Keep-Alive: timeout=15, max=86
Connection: Keep-Alive
Content-Length: 13356


I don't know (and don't want to know) why the HTTP server is not returning the headers in the same order each time (caused by chunked data ?), but I suspect that the .NET Framework (4.0) ignore the Content-Length header when it appears after the Connection one (highlighted in the above HTTP responses).

I've just decided to ignore the Content-Length header, letting the MemoryStream dynamically grow, and it works like a charm.

Better idea or suggestion?

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here