HttpWebResponse取不到Cookie?原来是因为被跳转了

今天做模拟登陆的时候,发现HttpWebResponse的Cookie都为空,但是Fiddler看是有的。。。后来看见是302状态,才知道请求这个的时候,Response回来已经是跳转了。。。这样Cookie就会消失。

解决方法:

1. 

var request = (HttpWebRequest)WebRequest.Create(URL));

request.CookieContainer = new CookieContainer(); //这句大家都知道,如果想要获得response的cookie,这句必须写。
request.AllowAutoRedirect = false;

2. 如果用的是WebClient,就需要重写这个类:

 public class WebClientEx : WebClient
    {
        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = (HttpWebRequest)base.GetWebRequest(address);
            request.AllowAutoRedirect = false;
            return request;
        }
    }

  var webClient = new WebClientEx();

原文地址:https://www.cnblogs.com/handboy/p/3949614.html