使用 HttpClientFactory 安全吗? [英] Is it safe to use HttpClientFactory?

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

问题描述

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

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

遵循 Microsoft 文档,每次调用 HttpClientFactory.CreateClient() 时都会创建新的 HttpClient 对象,因此将值设置为 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 的解决方案.我们应该禁用主 HttpMessageHanlderCookieContainer(它是一个 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 安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆