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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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
    };
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x