CookieContainer confusion

17,541

It's because when you retrieve the response from the website, it automatically populates the cookie container you used for the request. You can test this out by seeing what cookies are present before and after the response:

//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();
Share:
17,541

Related videos on Youtube

Drazen Bjelovuk
Author by

Drazen Bjelovuk

// Passion project https://bookormovie.net/

Updated on June 04, 2022

Comments

  • Drazen Bjelovuk
    Drazen Bjelovuk almost 2 years

    From what I understand, the basic use of the CookieContainer to persist cookies through HttpWebRequests is as follows:

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

    then:

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

    But I'm having trouble understanding the logic behind this process. The variable cookies doesn't seem to have been reassigned anywhere after its initialization. How exactly do the cookies from the first WebResponse carry into the second WebRequest?

  • Drazen Bjelovuk
    Drazen Bjelovuk almost 12 years
    I see. Then would I be right to say that the statement "request.CookieContainer = cookies;" is simply passing a reference of the object "cookies" to request.CookieContainer rather than the data itself?
  • Ichabod Clay
    Ichabod Clay almost 12 years
    That sounds about right. If you need some brushing up on passing references/values, take a look at this article.
  • Drazen Bjelovuk
    Drazen Bjelovuk almost 12 years
    Very much appreciated. Thank you. =)