Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use HttpClientFactory?

In my asp.net core MVC application, I'm using HttpClientFactory to create HttpClient object for requests to API server.

Follows Microsoft document, HttpClient object is created new for each time I call HttpClientFactory.CreateClient(), so it will be safe for setting values to HttpClient.DefaultRequestHeaders.

About HttpMessageHandler objects, because they are pooled and can be re-used later. So, if they hold cookies information (For example: setting cookies to HttpClientHandler object), we will violate thread-safe.

Is my assumption is correct? How could we deal with this problem?

Is it OK if we set cookie in HttpRequestMessage, then we will send it with HttpClient?

like image 655
tuq Avatar asked Dec 21 '18 08:12

tuq


People also ask

Is HttpClientFactory thread safe?

HttpClient is a mutable object but as long as you are not mutating it, it is actually thread safe and can be shared.

What is the use of HttpClientFactory?

Not only that HttpClientFactory can create and manage new HttpClient instances but also, it works with underlying handlers. Basically, when creating new HttpClient instances, it doesn't recreate a new message handler but it takes one from a pool. Then, it uses that message handler to send the requests to the API.

What are the differences between HttpClientFactory and HttpClient?

It has a method CreateClient which returns the HttpClient Object. But in reality, HttpClient is just a wrapper, for HttpMessageHandler. HttpClientFactory manages the lifetime of HttpMessageHandelr, which is actually a HttpClientHandler who does the real work under the hood.

Is AddHttpClient transient?

In the preceding code, AddHttpClient registers GitHubService as a transient service. This registration uses a factory method to: Create an instance of HttpClient .


1 Answers

I have found the solution to use HttpClientFactory. We should disable CookieContainer of primary HttpMessageHanlder (it's a HttpClientHandler):

services.AddHttpClient("configured-inner-handler")
.ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler()
    {
        UseCookies = false
    };
});
like image 86
tuq Avatar answered Sep 21 '22 03:09

tuq