Saturday, March 2, 2013

WebRequest.GetResponse causes the application to hang

Recently I built an application which required the use of the WebRequest type. When calling GetResponse to retrieve the response stream all was working fine. By mistake, I incorrectly created the application targetting .Net 4.0 - so I changed the target framework to 3.5 and all was not working fine. When GetResponse was called, the application hung, and looking through Fiddler no request was actually made to the http server. 

After some googling, I found this is a common scenario where GetResponse hangs when not targetting .Net 4.0. Solutions I found to this issue varied, however the one that worked for me was looking at the MSDN example for using the WebRequest type and comparing line by line to how I was using WebRequest.

Turns out, the only difference was I wasn't specifying the Content-Length http header:

webRequest.ContentLength = byteArray.Length;

Once the above was included when setting up the WebRequest - GetResponse no longer hanged when targetting 3.5 (and continues to work fine when targetting 4.0).

The 4.0 WebRequest version is obviously more forgiving and allows you not to specify the Content-Length (and I'm assuming calculates automatically).