How to read response cookies using System.Net.Http.HttpClient?
Posted On: 18-Jan-2022 05:53
Some time we need to access/get few response values from cookies returned by api service provider or some auth provider. To solved this problem .net providing HttpClientHandler.CookieContainer and can be pass as handler argument in HttpClient.
The CookieContainer property provides an instance of the CookieContainer class that contains the cookies associated with this handler.
If the UseCookies property is true, the CookieContainer property represents the cookie container used to store the server cookies. The user can set custom cookies before sending requests using this property. If the UseCookies property is false and the user adds cookies to CookieContainer, cookies are ignored and not sent to the server. Setting the CookieContainer to null will throw an exception. Refer here for more detail: cookiecontainer
Followig are the codes/steps to receive cookies from server:
- Create an instance of HttpClientHandler
- Pass HttpClientHandler instance as argument during HttpClient object creation.
- After the request is made the cookie container will automatically be populated with all the cookies from the response. Now, we can then call GetCookies() to retreive them.
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var client = new HttpClient(handler);
var response = client.GetAsync("http://google.com").Result;
Uri uri = new Uri("http://google.com");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
Console.WriteLine(cookie.Name + ": " + cookie.Value);