WebClient StatusCode

时间:2012-11-19 23:10:48

标签: c# webclient http-status-code-302

我正在使用WebClient从有时不可用的页面获取一些信息[302 Moved Temporarily]。所以我想编程以检测页面是否存在

我尝试使用以下代码覆盖WebClient WebResponse,只有在状态正常时才返回页面,但它没有用。

protected override WebResponse GetWebResponse(WebRequest request)
{
    var response = base.GetWebResponse(request);

    if (response is HttpWebResponse)
        return (response as HttpWebResponse).StatusCode == HttpStatusCode.OK ? response : null;
    return null;
}

当我使用我的overriden类来获取页面时(当它不可用时)它只是重定向并且没有返回null

获取代码

private async Task<string> Get(string uri)
{
    return await Handler.DownloadStringTaskAsync(new Uri(uri));
}

[我想要实现的目标]:我希望网络客户端尝试获取该页面,但未找到它,因此已将其重定向到另一页面。

2 个答案:

答案 0 :(得分:1)

默认情况下,

WebClient会自动跟踪重定向(最多可达到最大数量)。

如果您覆盖GetWebRequest来修改返回的HttpWebRequest,将其AllowAutoRedirect属性设置为false,那么我相信它会直接返回302 - 尽管可能是异常...

答案 1 :(得分:0)

这不会告诉您状态,但可以通过您被重定向的事实来推断。

if(reponse.ResponseUri != request.RequestUri) {
   // if you really want to know the status
   // set AllowAutoRedirect = false;
   // and send another request in here.
}