Is it safe to use HttpClientFactory?

蹲街弑〆低调 提交于 2019-12-04 03:19:07

问题


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?


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


来源:https://stackoverflow.com/questions/53881531/is-it-safe-to-use-httpclientfactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!