【问题标题】:Is it safe to use HttpClientFactory?使用 HttpClientFactory 是否安全?
【发布时间】:2018-12-21 08:38:12
【问题描述】:

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

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

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

我的假设是正确的吗?我们该如何处理这个问题?

如果我们在HttpRequestMessage中设置cookie可以吗,那么我们将使用HttpClient发送它?

【问题讨论】:

  • 如果您需要操作标头和/或 cookie 等,您应该使用 1 个 HttpClient 实例并使用 SendAsync。阅读更多here。注意,文章只强调问题,如果需要操作HttpClient中的各种共享状态信息需要使用SendAsync来代替。
  • @LasseVågsætherKarlsen,在asp.net核心中,我们应该使用HttpClientFactory来创建HttpClient对象。正如你所说,我们也可以对HttpClient 使用单例,但这会导致问题:github.com/dotnet/corefx/issues/11224。我只是想知道我们是否使用HttpClientFactory,池化的HttpClientHandler 对象可能会导致线程安全问题。
  • CookieContainer 类本身是线程安全的。当cookie容器操作cookies数组时,您可以see the code yourself。
  • @SimplyGed,也许 CookieContainer 本身是线程安全的,但是在 HttpClientFactory 的情况下使用时,可能会导致问题。例如:1. HttpClient1 send request to API api/checkAccessStatus => 2. API check if Request1.Cookie contains "HasAccessed" key, if not, set Response.Cookie["HasAccessed"] = true => 3. (From other user) HttpClient2 send request to API api/checkAccessStatus => 4. Since HttpClient2 is created with HttpClientFactory, it can have same HttpHandler (same CookieContainer). API will see that Request.Cookie["HasAccessed"] is true => 错误

标签: asp.net asp.net-core .net-core dotnet-httpclient httpclientfactory


【解决方案1】:

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

services.AddHttpClient("configured-inner-handler")
.ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler()
    {
        UseCookies = false
    };
});

【讨论】:

    猜你喜欢
    • 2012-02-22
    • 2016-05-12
    • 2010-11-23
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 2013-09-20
    相关资源
    最近更新 更多