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

Views: 10224
Comments: 6
Like/Unlike: 3
Posted On: 18-Jan-2022 05:53 

Share:   fb twitter linkedin
2232 Points
14 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.


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("").Result;

Uri uri = new Uri("");
IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
    Console.WriteLine(cookie.Name + ": " + cookie.Value);





31-Jan-2022 at 22:45

great man!

01-Sep-2022 at 02:38


Mails Backup
14-Oct-2022 at 12:09

Very nice!

19-Apr-2023 at 06:29


10-Oct-2023 at 06:33


25-Oct-2023 at 22:29
 Log In to Chat