0

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...

UweB
  • 4,080
  • 2
  • 16
  • 28
  • 1
    How many _concurrent_ users are you expecting at any given time? Unless it's in the thousands you shouldn't need to worry about port exhaustion. Don't take the advice to extremes. You don't want to create an `HttpClient` instance per _request_, but you should be fine with an instance per _user_. – Todd Menier Oct 11 '19 at 02:16
  • I am starting to think you are right, despite the seemingly strict advice in Microsoft's documentation. The thing is, since my code will not necessarily run inside a service class, I can't necessarily take their example code as template. Worse comes to worst, I can always handle authentication/cookies/redirects myself, if resources are becoming an issue. Thank you! – UweB Oct 13 '19 at 12:40

0 Answers0