如何在 C# 中有效地检查来自 URL 的 401 响应?
我想创建一个方法来确定特定 URL 是否可以匿名使用。我这样做是为了从自定义搜索页面中删除无法访问的结果。我能想到的最好的办法是
public bool IsWebAddressAccessible(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
然而,由于两个原因,这并不理想。首先,据我了解,以这种方式依赖异常进行逻辑效率不高。其次,在页面可访问的情况下,似乎要检索整个页面,这很耗时。所以问题是:
- 有没有一种方法可以在不依赖异常的情况下做到这一点?
- 有没有办法加快速度,这样我就可以查看响应是否返回 401,而无需等待检索整个页面?
I would like to create a method that determines if a particular URL is available anonymously. I'm doing this in order to strip out inaccessible results from a custom search page. The best I can come up with is
public bool IsWebAddressAccessible(string Url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch (System.Net.WebException)
{
return false;
}
return true;
}
However, this is less than ideal for a few two reasons. Firstly, as I understand, it's not efficient to rely on exceptions for logic in this way. Secondly, in the case where the page is accessible, it seems to retrieve the whole page, which is time-consuming. So the questions are:
- Is there a way to do this without relying on exceptions?
- Is there a way to speed this up so I can just see whether the response is coming back as 401 or not without waiting to retrieve the entire page?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个令人烦恼的异常 在HttpWebRequest的设计中。实际上,我的一个项目中有几个扩展方法(其中一个会发出大量请求,预计会返回 304 未修改):
<前><代码>[调试器非用户代码]
公共静态 HttpWebResponse GetHttpResponse(此 HttpWebRequest 请求){
// 我们知道响应将是 HttpWebResponse 因为请求是 HttpWebRequest
返回 (HttpWebResponse)request.GetResponse();
}
[调试器非用户代码]
公共静态 HttpWebResponse GetHttpResponseAvoidVusingExceptions(此 HttpWebRequest 请求){
尝试 {
返回 GetHttpResponse(请求);
} catch (WebException ex) {
HttpWebResponse 响应 = (HttpWebResponse)ex.Response;
开关(响应.StatusCode){
案例 HttpStatusCode.NotModified:
返回响应;
默认:
// 我们不捕获其他异常
扔;
}
}
}
我不知道如何避免此异常。
HEAD
方法仅获取响应标头。this is a vexing exception in the design of HttpWebRequest. I've actually got a couple of extension methods in one of my projects (one that makes a lot of requests that are expected to return 304 not modified):
There's no way I'm aware of to avoid this exception.
HEAD
method to only get back the response headers.