我试图验证使用HttpWebRequest的URL的存在。 我发现,这样做基本上这几个例子:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);
request.Method = "HEAD";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
return response.StatusCode;
}
但是,如果该网址是否确实破裂,它没有返回响应,它的而不是抛出异常。
我修改我的代码如下:
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;
}
这似乎终于做我想做的。
不过,我想知道,为什么请求抛出异常而不是返回NOTFOUND状态码的响应?