C# keep session id over httpwebrequest

If you create a single cookie container and assign that to both your first and second request you won’t need to do all that mucking about copying cookies from the response.

When cookies are set by a response the cookie container that is attached the request will receive and store those cookies. So to maintain the same session context between a series of request just maintain a single cookie container instance and use that with all the requests.

Your code becomes:-

cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
  // Do stuff with response
}

then:-

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
...

request.CookieContainer = cookieContainer;
Stream writeStream = request.GetRequestStream()

Leave a Comment