问题描述
我正在尝试使用HttpWebRequest验证网址的存在。我发现了一些基本上可以做到这一点的示例:
I'm trying to verify the existence of a Url using HttpWebRequest. I found a few examples that do basically this:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
return response.StatusCode;
}
但是,如果URL确实损坏,则不会返回响应,而是
However, if the url is indeed broken, it's not returning a response, it's instead throwing an exception.
我将代码修改为:
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
return response.StatusCode;
}
}
catch (System.Net.WebException ex)
{
var response = ex.Response as HttpWebResponse;
return response == null ? HttpStatusCode.InternalServerError : response.StatusCode;
}
这似乎终于可以满足我的要求。
which seems to finally do what I want.
但是我想知道,为什么请求抛出异常而不是返回带有NotFound状态码的响应?
But I would like to know, why is the request throwing an exception instead of returning the response with a NotFound status code?
推荐答案
是的,当网页大量使用状态代码并且并非全部都是错误时,这可能会很烦人。这会使身体加工变得很痛苦。我个人使用此扩展方法来获取响应。
Ya this can be quite annoying when web pages use status codes heavily and not all of them are errors. Which can make processing the body quite a pain. Personally I use this extension method for getting the response.
public static class HttpWebResponseExt
{
public static HttpWebResponse GetResponseNoException(this HttpWebRequest req)
{
try
{
return (HttpWebResponse)req.GetResponse();
}
catch (WebException we)
{
var resp = we.Response as HttpWebResponse;
if (resp == null)
throw;
return resp;
}
}
}
这篇关于为什么HttpWebRequest抛出异常而不返回HttpStatusCode.NotFound?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!