Search code examples
c#httpclient

Clear a CookieContainer


I want to clear all cookies in my CookieContainer. If I do this:

CookieContainer cookieContainer = new CookieContainer();
var handler = new HttpClientHandler { CookieContainer = cookieContainer };
var httpClient = new HttpClient(handler);
// make some requests
cookieContainer = new CookieContainer();

Will the httpClient have the new (empty) cookieContainer, or I have to re-create my httpClient?


Solution

  • Notice that you're updating the local reference, but not the reference to the CookieContainer in the HttpClientHandler. You can see in the answer below the only way to expire cookies in a CookieContainer, setting the Expires property to a past DateTime.

    How to remove cookies under 1 domain in CookieContainer

    Creating a fresh HttpClient can also fix it if performance is not something you care about.