This answer shows how to add a cookie to an HttpClient request. But one of the comments warns that CookieContainer
is cached on the HttpClient. Most of my cookies should not be sent again for a different user.
I am hoping that the HttpClientFactory
cleans things like added CookieContainer
s off the instance of the HttpClient that is in its pool.
If I get my HttpClient
by calling httpClientFactory.CreateClient
is there a chance that the one I get will have a previous CookieContainer
on it?
Update:
The answer to my question is yes! CookieContainer
is intended for when you want to send the same cookie with every call.
If you need to send a different cookie with each call, there are several ways to do that. But the easiest is to put it in the header.
Because the HttpClientFactory
creates a new HttpClient
with each request for a client, you can add to the headers of the client and not worry about it reusing the cookie.
The key to doing this is the setting UseCookies
. It HAS to be set to false or the cookies you add to the headers will be ignored. Once you do that, you can add the cookies to your header under the key "Cookies" and enter them as semicolon separated key value pairs (with an equal sign between them). Your cookies come back in the header "Set-Cookies".
It's the HttpMessageHandler
instances that get pooled; not the HttpClient
instances. By default, the handlers have a lifetime of 2 minutes, which means it's very possible that a CookieContainer
will be shared between multiple HttpClient
s.
There's a section in the official docs, which explains that automatic cookie handling and IHttpClientFactory
don't work well together:
The pooled
HttpMessageHandler
instances results inCookieContainer
objects being shared. UnanticipatedCookieContainer
object sharing often results in incorrect code. For apps that require cookies, consider either:
- Disabling automatic cookie handling
- Avoiding
IHttpClientFactory
Call ConfigurePrimaryHttpMessageHandler to disable automatic cookie handling:
services.AddHttpClient("configured-disable-automatic-cookies") .ConfigurePrimaryHttpMessageHandler(() => { return new SocketsHttpHandler() { UseCookies = false, }; });