简体   繁体   中英

HttpWebResponse.StatusCode isn't trapping 500 Errors

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 following.

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...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM