How to read cookies from HttpResponseMessage?

34,064

Solution 1

The issue I have with many of the answers here is that using CookieContainer uses short-lived HttpClient objects which is not recommended.

Instead, you can simply read the "Set-Cookie" header from the response:

// httpClient is long-lived and comes from a IHttpClientFactory
HttpResponseMessage response = await httpClient.GetAsync(uri);
IEnumerable<string> cookies = response.Headers.SingleOrDefault(header => header.Key == "Set-Cookie")?.Value;

Solution 2

Try this:

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

HttpClient authClient = new HttpClient(handler);

var uri = new Uri("http://localhost:4999/test_db/_session");

authClient.BaseAddress = uri;
authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var user = new LoginUserSecretModel
{
    name = userKey,
    password = loginData.Password,
};

HttpResponseMessage authenticationResponse = authClient.PostAsJsonAsync("", user).Result;

var responseCookies = cookies.GetCookies(uri).Cast<Cookie>();

Solution 3

This is what you need to get a list of cookies;

    private async Task<List<Cookie>> GetCookies(string url, string cookieName)
    {
        var cookieContainer = new CookieContainer();
        var uri = new Uri(url);
        using (var httpClientHandler = new HttpClientHandler
        {
            CookieContainer = cookieContainer
        })
        {
            using (var httpClient = new HttpClient(httpClientHandler))
            {
                await httpClient.GetAsync(uri);
                List<Cookie> cookies = cookieContainer.GetCookies(uri).Cast<Cookie>().ToList();
                return cookies;
            }
        }
    }

and if you need only one cookie value here's how

 private async Task<string> GetCookieValue(string url)
        {
            var cookieContainer = new CookieContainer();
            var uri = new Uri(url);
            using (var httpClientHandler = new HttpClientHandler
            {
                CookieContainer = cookieContainer
            })
            {
                using (var httpClient = new HttpClient(httpClientHandler))
                {
                    await httpClient.GetAsync(uri);
                    var cookie = cookieContainer.GetCookies(uri).Cast<Cookie>().FirstOrDefault(x => x.Name == cookieName);
                    return cookie?.Value;
                }
            }
        }

Solution 4

Building on top of Daniel's answer and this answer to another question, this would be an easy way to read the cookies from an HTTP response.

// httpClient is long-lived and comes from a IHttpClientFactory
HttpResponseMessage response = await httpClient.GetAsync(uri);
CookieContainer cookies = new CookieContainer();
foreach (var cookieHeader in response.Headers.GetValues("Set-Cookie"))
    cookies.SetCookies(uri, cookieHeader);
string cookieValue = cookies.GetCookies(uri).FirstOrDefault(c => c.Name == "MyCookie")?.Value;
Share:
34,064
mmh18
Author by

mmh18

Updated on January 03, 2022

Comments

  • mmh18
    mmh18 over 2 years

    This is my recent code:

    HttpClient authClient = new HttpClient();
    authClient.BaseAddress = new Uri("http://localhost:4999/test_db/_session");
    authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
    var user = new LoginUserSecretModel
    {
        name = userKey,
        password = loginData.Password,
    };
    HttpResponseMessage authenticationResponse = authClient.PostAsJsonAsync("", user).Result;
    
  • mmh18
    mmh18 about 9 years
    thank you for your answer .... but "cookie" count was 0 and nothing containing when i get HttpResponseMassage.
  • RagtimeWilly
    RagtimeWilly about 9 years
    Are you sure cookies are being set?
  • mmh18
    mmh18 about 9 years
    yes i already set, i found the cookies are in authenticationResponse.headers.
  • RagtimeWilly
    RagtimeWilly about 9 years
    Are the cookies secure? See here: stackoverflow.com/questions/14681144/…
  • dsample
    dsample over 7 years
    cookies is a different object to authenticationResponse. The cookies object is just an empty object. CookieContainer is just a data structure for cookies to be put into... this answer does not put anything into it from the authenticationResponse object.
  • JustAMartin
    JustAMartin almost 5 years
    Also, if you are using HttpClient as a shared instance for many parallel requests (as it is recommended aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong ) , be aware that cookies in the handler might belong to a different parallel response, not the one you just received. Unless you do some locking for every request to avoid such cookie race conditions.
  • Chatonne
    Chatonne about 4 years
    Once we get the "cookies" string, is there a clean way to obtain a specific cookie value? It feels a bit clunky to have to parse the string to extract the actual cookie value. I assume there's probably be a helper method in .Net to handle it, but most of my researches circle back to CookieContainer which we can't use when reusing our HttpClient instance.
  • justian17
    justian17 about 4 years
    Best answer if a person wants to have both a response and the cookies from that response. In my humble opinion, parsing the string is trivial.
  • cubesnyc
    cubesnyc over 3 years
    KeyValuePair is not nullable