Reusing HttpClient for different users

I read a lot about best practices when using HttpClient . Most people recommend reusing it throughout the life of the application, even if it is IDisposable .

My web application interacts with various APIs such as Facebook API, Twitter API and Instagram API.

The plan is to create a separate HttpClient for each API that it communicates with, 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 access token). I believe this means that I cannot set the authorization header for the DefaultRequestHeaders of the HttpClient object.

What is the best practice of reusing HttpClient for multiple users who have different privilege headers?

Can I create an HttpRequestMessage object for each request and set the authorization header in the httpRequestMessage object instead of setting it to the default, httpClient.DefaultRequestHeaders.Authorization ?

Thanks.

+6
source share
1 answer

Because there are some costs to creating an HttpClient (especially the number of sockets), there are some advantages to reusing an instance of HttpClient . It is also thread safe.

To avoid dependencies between several simultaneous calls with one client instance, the key template should use the HttpRequestMessage and call HttpClient.SendAsync (instead of using the more convenient HttpClient.GetAsync , PostAsync , ...).

Something like that:

 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 HttpRequestMessage request headers will be used (and not DefaultRequestHeaders ).

+7
source

Source: https://habr.com/ru/post/1012488/


All Articles