向通过IHttpClientFactory创建的所有客户端添加处

向通过IHttpClientFactory创建的所有客户端添加处

本文介绍了向通过IHttpClientFactory创建的所有客户端添加处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以向IHttpClientFactory创建的所有客户端添加处理程序?我知道您可以在指定的客户端上执行以下操作:

Is there a way to add a handler to all clients created by the IHttpClientFactory? I know you can do the following on named clients:

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
});

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

But I don't want to use named clients I just want to add a handler to all clients that are given back to me via:

clientFactory.CreateClient();

推荐答案

使用不带参数的CreateClient时,您隐含请求一个命名客户端,该客户端的名称为 Options.DefaultName (string.Empty).要影响此默认实例,请在调用AddHttpClient时指定Options.DefaultName:

When you use CreateClient with no parameters, you implicitly request a named client, where the name is Options.DefaultName (string.Empty). To affect this default instance, specify Options.DefaultName when calling AddHttpClient:

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

这篇关于向通过IHttpClientFactory创建的所有客户端添加处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:55