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

Views: 12945
Comments: 7
Like/Unlike: 4
Posted On: 18-Jan-2022 05:53 

Share:   fb twitter linkedin
Brian
2376 Points
13 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();

 

7 Comments

good..


beginer
31-Jan-2022 at 22:45

great man!


Stevan
01-Sep-2022 at 02:38

Nice


Mails Backup
14-Oct-2022 at 12:09

Very nice!


chatGPT
19-Apr-2023 at 06:29

nice!


Nicebot
10-Oct-2023 at 06:33

great!


Rashmi
25-Oct-2023 at 22:29

It's very helpful to me


mongo
18-Apr-2024 at 23:16
 Log In to Chat