CookieContainer混乱

时间:2012-08-19 06:21:52

标签: c# session httpwebrequest cookiecontainer

据我所知,CookieContainer通过HttpWebRequests持久化Cookie的基本用法如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
  // Do stuff with response
}

然后:

request = (HttpWebRequest)WebRequest.Create(new url);
request.CookieContainer = cookies;
etc...

但我无法理解这个过程背后的逻辑。变量cookie在初始化后似乎没有被重新分配。第一个WebResponse的cookie到底是如何进入第二个WebRequest的?

1 个答案:

答案 0 :(得分:6)

这是因为当您从网站检索响应时,它会自动填充您用于请求的cookie容器。您可以通过查看响应之前和之后存在的cookie来测试这一点:

//Build the request
Uri site = new Uri("http://www.google.com");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;

//Print out the number of cookies before the response (of course it will be blank)
Console.WriteLine(cookies.GetCookieHeader(site));

//Get the response and print out the cookies again
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    Console.WriteLine(cookies.GetCookieHeader(site));
}

Console.ReadKey();