使用HttpClientFactory安全吗

使用HttpClientFactory安全吗

本文介绍了使用HttpClientFactory安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的asp.net核心MVC应用程序中,我使用 HttpClientFactory 创建 HttpClient 对象以请求API服务器。

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

按照Microsoft文档,每次调用 HttpClientFactory时,都会创建新的 HttpClient 对象。 CreateClient(),因此将值设置为 HttpClient.DefaultRequestHeaders 是安全的。

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.

关于 HttpMessageHandler 对象,因为它们是池中的,以后可以重用。因此,如果它们包含cookie信息(例如:将cookie设置为 HttpClientHandler 对象),我们将违反线程安全。

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?

如果我们在 HttpRequestMessage 中设置cookie,可以了吗?它与 HttpClient

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

推荐答案

我找到了使用HttpClientFactory的解决方案。我们应该禁用主要 HttpMessageHanlder CookieContainer (这是 HttpClientHandler ):

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

这篇关于使用HttpClientFactory安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:16