Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop .Net HttpWebRequest.GetResponse() raising an exception

Surely, surely, surely there is a way to configure the .Net HttpWebRequest object so that it does not raise an exception when HttpWebRequest.GetResponse() is called and any 300 or 400 status codes are returned?

Jon Skeet does not think so, so I almost dare not even ask, but I find it hard to believe there is no way around this. 300 and 400 response codes are valid responses in certain circumstances. Why would we be always forced to incur the overhead of an exception?

Perhaps there is some obscure configuration setting that evaded Jon Skeet? Perhaps there is a completely different type of request object that can be used that does not have this behavior?

(and yes, I know you can just catch the exception and get the response from that, but I would like to find a way not to have to).

Thanks for any help

like image 526
James Avatar asked Apr 23 '10 21:04

James


2 Answers

If you want to retrieve the error response from 4xx errors you can do it like this:

HttpWebResponse res = null;
string response = string.Empty;
StreamReader sr = null;
Stream resst = null;
try
{
    res = (HttpWebResponse)req.GetResponse();
    resst = res.GetResponseStream();
    sr = new StreamReader(resst);
    response = sr.ReadToEnd();
}
catch (WebException exception)
{
    HttpWebResponse errorResponse = (HttpWebResponse)exception.Response;
    resst = errorResponse.GetResponseStream();
    sr = new StreamReader(resst);
    response = sr.ReadToEnd();
}
this.Response.Write(response);

Hope this helps...

like image 126
dgivoni Avatar answered Sep 28 '22 18:09

dgivoni


According to the specification when a server sends a 400 status code it means that:

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

So it looks pretty natural to have an exception in this case. As far as 300 is concerned it is more debatable.

Anyway, if you want some non-standard behavior you can always resort to a TcpClient but that really seems like an extreme and desperate measure.

Did you perform performance tests? Have you confirmed that throwing an exception in this exceptional case is a bottleneck to your application? It seems like a micro optimization in this case. Can't you make this web server happy by forging a valid request and getting 200 at the end? If not can't you switch to a more standard web server?

like image 45
Darin Dimitrov Avatar answered Sep 28 '22 16:09

Darin Dimitrov