Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read cookies from HttpResponseMessage?

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; 
like image 920
mmh18 Avatar asked Mar 24 '15 03:03

mmh18


People also ask

How do I get HTTP responses from cookies?

Procedure. Use the HTTP request object that is passed to the service method of your servlet to get all cookies that the client browser sent with the request. 1. Use the getCookies() method of the HttpServletRequest to retrieve an array of all cookies in the request.

How to use cookies in asp net?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With ASP, you can both create and retrieve cookie values.

How do I get cookies on Web API?

Cookies in Web API To add a cookie to an HTTP response, create a CookieHeaderValue instance that represents the cookie. Then call the AddCookies extension method, which is defined in the System.


1 Answers

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; 
like image 122
Daniel Avatar answered Sep 28 '22 05:09

Daniel