mercredi 2 janvier 2013

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 ?

Aucun commentaire: