向通过 IHttpClientFactory 创建的所有客户端添加处理程序?

Haw*_*zey 14 c# dotnet-httpclient asp.net-core httpclientfactory

有没有办法向 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
});
Run Code Online (Sandbox Code Playgroud)

但我不想使用命名客户端,我只想向通过以下方式返回给我的所有客户端添加一个处理程序:

clientFactory.CreateClient();
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 15

当您CreateClient不带参数使用时,您隐式地请求一个命名的客户端,其中名称是Options.DefaultName( string.Empty)。要影响此默认实例,请Options.DefaultName在调用时指定AddHttpClient

services.AddHttpClient(Options.DefaultName, c =>
{
    // ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    // ...
});
Run Code Online (Sandbox Code Playgroud)

Tobias J在评论中指出 API 文档AddHttpClient声明如下:

使用DefaultName作为名称来配置默认客户端。

  • @janw的[文档](https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.httpclientfactoryservicecollectionextensions.addhttpclient?view=dotnet-plat-ext-3.1#Microsoft_Extensions_DependencyInjection_HttpClientFactoryServiceCollectionExtensions_AddHttpClient_Microsoft_Extensions_DependencyInjection_IServiceCollection_System_String_)用于` AddHttpClient` 重载采用名称参数,指定 `Options.DefaultName` 确实用作默认名称。 (2认同)