2

我有这个代码:

class CustomWebclient: WebClient
{
  [System.Security.SecuritySafeCritical]
  public CustomWebclient(): base()
 {
 }
 public CookieContainer cookieContainer = new CookieContainer();


 protected override WebRequest GetWebRequest(Uri myAddress)
 {
       WebRequest request = base.GetWebRequest(myAddress);
       if (request is HttpWebRequest)
      {
           (request as HttpWebRequest).CookieContainer =   cookieContainer;
           (request as HttpWebRequest).AllowAutoRedirect = true;
      }
      return request;
  }
}

当我加载页面 example.com 时,我得到:

Server: nginx
Date: Fri, 23 Aug 2013 05:24:44 GMT
Content-Type: text/html; charset=utf-8
Transfer-Encoding: chunked
Connection: close
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
location: /examplePage

但我的 CustomWebclient 不遵循重定向。为什么?该怎么做才能修复它?

可能它没有工作,因为“位置”是小写的。

4

1 回答 1

1

您的代码在我的测试下运行良好。

当提供正确的 cookie 时,我的测试站点 weibo.com 将通过 HTTP 302 强制重定向。

关闭自动重定向后,响应标头为

Transfer-Encoding: chunked
Connection: close
Pramga: no-cache
DPOOL_HEADER: dagda24
Cache-Control: no-cache, must-revalidate
Content-Type: text/html
Date: Thu, 13 Mar 2014 15:07:53 GMT
Expires: Mon, 26 Jul 1997 05:00:00 GMT
Last-Modified: Thu, 13 Mar 2014 15:07:53 GMT
Location: /u/2398332747/home?wvr=5
Server: nginx

并且网页没有明显重定向。

启用自动重定向后,响应标头是,

Transfer-Encoding: chunked
Connection: close
Vary: Accept-Encoding
Pragma: no-cache
DPOOL_HEADER: balor165
Cache-Control: no-cache, must-revalidate
Content-Type: text/html; charset=utf-8
Date: Thu, 13 Mar 2014 15:13:26 GMT
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Server: nginx

网页内容验证请求是否被重定向。

我确实注意到 Location 标头的第一个字母是大写的。这没有测试标题格式是否相关。

编辑:

最后,example.com 经过测试,但在我的环境下它根本不会触发重定向。这就是为什么我选择了weibo.com作为替代方案。

编辑:

我对此进行了更多研究,根据 RFC 2616,标头不区分大小写。您的代码对我来说很好,仍然不知道为什么会出错。希望别人给点指导意见。

于 2014-03-13T15:17:30.247 回答