According to https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client:
HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors:
- Creating a new HttpClient instance per request.
- Server under heavy load.
I want to follow that guideline and allow multiple users to share that sole HttpClient
instance, however the REST-service requires user-specific cookies (authentication purposes).
Then I found this in the comments on StackOverflow:
However, in discussions on the .NET GitHub it was brought to my attention that the problem does not lie in the HttpClient being disposed, but rather the HttpClientHandler.
That would mean that you can instantiate/dispose HttpClient
often as long as you ensure that you are not wasteful with your HttpClientHandler
instances. Keeping one HttpClientHandler
per user would allow me to keep different users' cookies apart, but it also wouldn't eliminate the problem described above...
So I guess my question is:
Is the following really the only way to do this? (idea again taken from a StackOverflow response)
- Use one global
new HttpClient(new HttpClientHandler { UseCookies = false }}
- Pluck the
Set-Cookie
value from the HTTP header of the authentication response and store it on a per-user basis ("session object") - Pass those cookies along with every individual request?
This seems terribly inconvenient...