How do I get the current cookie / session ID from a HttpResponseMessage?

silverfighter picture silverfighter · Nov 8, 2012 · Viewed 11.7k times · Source

I try to use the new .net 4.5 HttpClient from System.net.http.

I set-up my client like this

CookieContainer cookieJar = new CookieContainer();
         HttpClientHandler handler = new HttpClientHandler
         {
             CookieContainer = cookieJar,
             AllowAutoRedirect = true
         };
         handler.UseCookies = true;
         handler.UseDefaultCredentials = false;

         HttpClient client = new HttpClient(handler as HttpMessageHandler);

then I do a client.GetAsync(url)

now I am inspecting the response and try to get the cookie / session values for a following post.

I try to test a login scenario of an existing page via code...

How do I get the cookie information in a response? Or do I walk on a wrong path here? Any explanation would be fantastic...

Answer

Chris B. Behrens picture Chris B. Behrens · Aug 27, 2014

The cookie exists in the form of a header that is the instruction to create the cookie on the client. Those headers have the form of "Set-Cookie" as the actual header, with the value of "CookieTitle={form encoded value}". Getting that cookie looks like this:

var cookieTitle = "MyCookieTitle";

var response = ... // get response object
var cookie = response.Headers.GetValues("Set-Cookie").First(x => x.StartsWith(cookieTitle));

That gets you the raw string of the header, which will look like this:

CookieTitle=this+is+the+value+of+the+cookie