How to turn on autoredirect for Webclient

2019-02-19 09:54发布

I have this code:

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;
  }
}

When i load page example.com, i get:

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

But my CustomWebclient doesnt follow redirect. Why? What to do to fix it?

May be it didnt work because "location" in lower case.

1条回答
趁早两清
2楼-- · 2019-02-19 10:51

Your code runs fine under my test.

My test site weibo.com will force redirect by HTTP 302 when proper cookies are provided.

With autoredirect off, the Response Headers are

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

and the web page is not redirected obviously.

With autoredirect on, the Response Headers are,

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

the web page contents verifies that the request is redirected.

I do notice that the Location header's first letter is capital. This is not tested whether header format is related.

Edit:

At last, example.com is tested but under my environment it doesn't trigger a redirection at all. That's why i picked weibo.com as the alternative.

Edit:

I did some more research on this and according to RFC 2616, headers are case-insensitive. Your code is fine to me, still don't know why it goes wrong. Hoping someone else give a lead.

查看更多
登录 后发表回答