How to read cookies from HttpResponseMessage?

mmh18 picture mmh18 · Mar 24, 2015 · Viewed 27k times · Source

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;

Answer

Daniel picture Daniel · Feb 21, 2020

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;