How to read response cookies using System.Net.Http.HttpClient?

Views: 2214
Comments: 2
Like/Unlike: 2
Posted On: 18-Jan-2022 05:53 

Share:   fb twitter linkedin
Brian
Moderator
48 Points
12 Posts

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.

[source: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/httpclient-message-handlers]

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:

  1. Create an instance of HttpClientHandler
  2. Pass HttpClientHandler instance as argument during HttpClient object creation.
  3. 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);

Console.ReadLine();

 

2 Comments

good..


beginer

great man!


Stevan
 Log In to Chat