HttpWebResponse.StatusCode 未捕获 500 错误
我的问题: HttpWebResponse.StatusCode 是否检测 Asp.Net 错误?主要是黄屏死机?
一些背景: 我正在开发一个简单的 c# 控制台应用程序,它将测试服务器和服务以确保它们仍然正常运行。我假设由于 HttpStatusCodes 是用 OK、Moved、InteralServerError 等枚举的,所以我可以简单地执行以下操作。
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;
}
然而今天早上我发现这不起作用。 ASP.Net 应用程序崩溃并显示黄屏死机,而我的应用程序似乎并不介意,因为 response.StatusCode 等于 HttpStatusCode.OK。
我缺少什么?
谢谢 // lance
更新 感谢乔恩,这似乎有效。
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException webexp)
{
response = (HttpWebResponse)webexp.Response;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GetResponse
将抛出一个WebException
错误 - 但您可以捕获WebException
,使用WebException.Response
获取响应,然后从那。据我所知,
GetResponse
从不返回 null,因此您可以从代码中删除该测试。此外,与其让 if/else 块返回 true/false,不如返回计算表达式的结果,例如:(
说实话,您可能会返回
false
if anyWebException
被抛出...)GetResponse
will throw aWebException
for errors - but you can catch theWebException
, useWebException.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:
(To be honest, you could probably return
false
if anyWebException
is thrown...)