Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing HttpClient for different users

I've been reading a lot about best practices when using HttpClient. Most people recommend reusing it for the lifetime of the application, even though it's IDisposable.

My web application is communicating with various APIs, like Facebook Graph API, Twitter API and Instagram API.

The plan is to create an individual HttpClient for each API it communicates to, which is recommended, because then I can reuse some of the headers.

But now to the question, let's take the Twitter API as an example, each user using my web application has its own authorization header (user bound access token). I believe this means that I can't set the authorization header to the DefaultRequestHeaders of the HttpClient object.

What is the best practice when it comes to reusing HttpClient for multiple users who have different authorization headers?

Could I create a HttpRequestMessage object for each request and set the authorization header on the httpRequestMessage object, instead of setting it to the default one, httpClient.DefaultRequestHeaders.Authorization?

Thanks.

like image 583
Jón Trausti Arason Avatar asked Nov 19 '16 18:11

Jón Trausti Arason


People also ask

Can HttpClient be reused?

NET documentation for HttpClient: HttpClient is intended to be instantiated once and re-used throughout the life of an application.

Should we create a new single instance of HttpClient for all requests?

The correct way as per the post is to create a single instance of HttpClient as it helps to reduce waste of sockets.

Can HttpRequestMessage be reused?

An HttpRequestMessage object can only be used one time; future attempts to use the same object throw an exception.

What happens if you don't dispose HttpClient?

Answer when NOT using HttpClientFactory: Generally, you don't want to dispose of HttpClient unless it's used very infrequently. Regular creation and disposal may lead to socket exhaustion.


1 Answers

Because there is some cost involved in creating a HttpClient (especially the number of sockets) there are some benefits in reusing a HttpClient instance. It is thread-safe as as well.

In order to have no dependencies between multiple concurrent calls with one client instance the key pattern is to use HttpRequestMessage class and invoke the HttpClient.SendAsync method (instead of using the more convenient HttpClient.GetAsync, PostAsync, ...).

Something like this:

var request = new HttpRequestMessage() {
   RequestUri = new Uri("http://api.twitter.com/someapiendpoint"),
   Method = HttpMethod.Get
}
// set the authorization header values for this call
request.Headers.Accept.Add(...);

var response = await client.SendAsync(request);

Now the request headers of the HttpRequestMessage will be used (and not the DefaultRequestHeaders anymore).

like image 170
Ralf Bönning Avatar answered Oct 17 '22 06:10

Ralf Bönning