有没有办法向 IHttpClientFactory 创建的所有客户端添加处理程序?
我知道您可以对指定客户执行以下操作:
services.AddHttpClient("named", c =>
{
c.BaseAddress = new Uri("TODO");
c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
c.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MaxAge = new TimeSpan(0),
MustRevalidate = true
};
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AllowAutoRedirect = false,
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});
但我不想使用命名客户端。
我只想向通过以下方式返回给我的所有客户端添加一个处理程序:
clientFactory.CreateClient();
当您使用不带参数的
CreateClient
时,您会隐式请求指定客户端,其名称为 Options.DefaultName
(string.Empty
)。
要影响此 default 实例,请在调用
Options.DefaultName
时指定 AddHttpClient
:
services.AddHttpClient(Options.DefaultName, c =>
{
// ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
// ...
});
的 API 文档说明如下:
使用 DefaultName 作为名称来配置默认客户端。