开发者

HttpWebResponse.StatusCode isn't trapping 500 Errors

开发者 https://www.devze.com 2023-01-29 07:44 出处:网络
My Question: Does a HttpWebResponse.StatusCode detect Asp.Net errors? Mainly a yellow screen of death?

My Question: Does a HttpWebResponse.StatusCode detect Asp.Net errors? Mainly a yellow screen of death?

Some Background: I am working on a simple c# console app that will test servers and services to make sure they are still functioning properly. I assumed since the HttpStatusCodes are enumerated with OK, Moved, InteralServerError, etc... that I could simply do the fol开发者_如何学运维lowing.

WebRequest request = WebRequest.Create(url);
request.Timeout = 10000;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response == null || response.StatusCode != HttpStatusCode.OK)
{
   // SERVER IS OK
   return false;
}
else
{
   // SERVER HAS SOME PROBLEMS
   return true;
}

I found out this morning however that this doesn't work. An ASP.Net application crashed showing a Yellow Screen Of Death and my application didn't seem to mind because the response.StatusCode equaled HttpStatusCode.OK.

What am I missing?

Thanks // lance

Update Thanks to Jon this seems to be working.

 HttpWebResponse response;
 try
 {
   response = (HttpWebResponse)request.GetResponse();
 }
 catch (WebException webexp)
 {
   response = (HttpWebResponse)webexp.Response;
 }


GetResponse will throw a WebException for errors - but you can catch the WebException, use WebException.Response to get the response, and then get the status code from that.

As far as I'm aware, GetResponse never returns null, so you can remove that test from your code.

Also, rather than having if/else blocks to return true/false, it's simple just to return the result of evaluating an expression, for example:

return response.StatusCode == HttpStatusCode.OK;

(To be honest, you could probably return false if any WebException is thrown...)

0

精彩评论

暂无评论...
验证码 换一张
取 消