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

adding a handler to all clients created via IHttpClientFactory?

有没有办法向 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 时,您 implicitly request a named client, where the name is Options.DefaultName (string.Empty)。要影响此 default 实例,请在调用 AddHttpClient:

时指定 Options.DefaultName
services.AddHttpClient(Options.DefaultName, c =>
{
    // ...
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    // ...
});

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

Use DefaultName as the name to configure the default client.