C# 如何从 URL 获取服务器错误?
我们有一个 url,我们需要检查网页是否处于活动状态。我们尝试了以下代码: WebResponse objResponse = null;
WebRequest objRequest = HttpWebRequest.Create(URL);
objRequest.Method = "HEAD";
try
{
objResponse = objRequest.GetResponse();
objResponse.Close();
}
catch (Exception ex)
{
}
如果无法获得响应,上面的代码会给出异常,但即使我们在该页面上出现“服务器错误”,也可以正常工作?有什么帮助如何获取服务器错误吗?
We have a url and we need to check whether web page is active or not. We tried following code:
WebResponse objResponse = null;
WebRequest objRequest = HttpWebRequest.Create(URL);
objRequest.Method = "HEAD";
try
{
objResponse = objRequest.GetResponse();
objResponse.Close();
}
catch (Exception ex)
{
}
Above code gave exception if unable to get a response but also works fine even if we have a "server error" on that page? Any help how to get server error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
HttpResponse
类有一个StatusCode
属性,您可以检查该属性。如果是200就一切正常了。您可以将代码更改为:
The
HttpResponse
class has aStatusCode
property which you can check. If it's 200 everything is ok.You can change your code to this:
一方面,在响应上使用
using
语句 - 这样无论发生什么,您都可以处理它。现在,如果抛出
WebException
,您可以捕获它并查看WebException.Response
以找出状态代码和发送回的任何数据:For one thing, use a
using
statement on the response - that way you'll dispose of it whatever happens.Now, if a
WebException
is thrown, you can catch that and look atWebException.Response
to find out the status code and any data sent back: