Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient not storing cookies in CookieContainer

I'm using VS2010 +.NET 4.0 + System.Net.Http (from Nuget).

For a reason which I don't manage to understand, the session cookie which I receive in my HttpResponseMessage is not automatically saved in the HttpClient CookieContainer. Here is what my code looks like:

CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
HttpClient client = new HttpClient(handler);

Uri site = new Uri("https://www.mywebsite.com");
var response1 = client.SendAsync(new HttpRequestMessage(HttpMethod.Get,site)).Result;

I can see in the response headers that I have the following:

Set-Cookie: JSESSIONID=FC8110E434C2C6DAB78B4E335024A639; Path=/member; Secure

However my cookie container remains empty ...why ?

like image 643
user2038596 Avatar asked Feb 04 '13 05:02

user2038596


2 Answers

Use this piece of code to retrieve cookies from response:

/// <summary>
/// Read web cookies
/// </summary>
public static CookieContainer ReadCookies(this HttpResponseMessage response)
{
    var pageUri = response.RequestMessage.RequestUri;

    var cookieContainer = new CookieContainer();
    IEnumerable<string> cookies;
    if (response.Headers.TryGetValues("set-cookie", out cookies))
    {
        foreach (var c in cookies)
        {
            cookieContainer.SetCookies(pageUri, c);
        }
    }

    return cookieContainer;
}
like image 122
Salar Avatar answered Oct 29 '22 16:10

Salar


I guess the problem is that your cookies are secure. The problem is that, CookieContainer won't send secure cookies back to the server in subsequent HTTP requests. It might be a bug, or maybe it has some reasons behind it.

A workaround is to re-add the cookie to CookieContainer manually. This way, cookie would be sent back in HTTP request header, as no secure would be defined when you send cookies back to the server.

See this article for more information.

like image 21
Saeed Neamati Avatar answered Oct 29 '22 16:10

Saeed Neamati