c# - 如何为 Webclient 开启自动重定向

标签 c# silverlight windows-phone-7 windows-phone webclient

我有这个代码:

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 不遵循重定向。 为什么?如何修复它?

可能是因为“location”是小写所以没用。

最佳答案

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

当提供适当的 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

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

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

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 header 的第一个字母是大写的。这个没有测试header格式是否相关。

编辑:

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

编辑:

我对此做了更多研究,根据 RFC 2616, header 不区分大小写。你的代码对我来说很好,仍然不知道为什么会出错。希望其他人提供线索。

关于c# - 如何为 Webclient 开启自动重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394761/

相关文章:

c# - Silverlight 4 BitmapImage 错误 : ImageOpened not invoked after SetSource()

c# - OOP 设计以及列表和集合 (C#)

c# - 整数溢出检测 C# for Add

c# - 是否可以重构此 nHibernate Linq 查询?

c# - 我想每秒显示数字时钟来刷新TextBox(Windows App)

c# - SoundEffect 在从 SpeechLib 分配缓冲区时引发错误

silverlight - View 、模型和 View 模型之间的常见关系是什么?

c# - 搜索文件内容以查找与正则表达式的匹配项

silverlight - WCF-RIA 服务客户端 OutputCache - 如何强制刷新缓存

silverlight - 更新 ObservableCollection 导致 "The Parameter is incorrect"异常