如何自动为所有 HttpClients 设置自定义 DelegatingHandler?

How to set custom DelegatingHandler to all HttpClients automatically?

我想为应用程序中的所有客户端使用 LoggingHttpClientHandler。我通过 named/typed 客户端

找到了唯一可用的方法

startup.cs

services.AddTransient<LoggingHttpClientHandler>();
services.AddHttpClient("clientWithLogging").AddHttpMessageHandler<LoggingHttpClientHandler>();

然后在每个服务中我都必须使用 var client = _clientFactory.CreateClient("clientWithLogging") 这有点不舒服。

LoggingHttpClientHandler.cs

public class LoggingHttpClientHandler : DelegatingHandler
{
    public LoggingHttpClientHandler(HttpMessageHandler innerHandler) : base(innerHandler)
    {
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (request.Content != null)
        {
            Logging.Log.Info(await request.Content.ReadAsStringAsync());
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

有没有办法不用命名每个客户端?

如果只是名字,还有扩展方法CreateClient that takes no arguments and uses the default name, which is string.Empty。 因此,您可以使用 string.Empty 作为名称注册服务,例如:

services.AddHttpClient(string.Empty).AddHttpMessageHandler<LoggingHttpClientHandler>();

并使用实例化客户端:

var client = _clientFactory.CreateClient();

问题在于解析 LoggingHttpClientHandler 的无用构造函数中的参数。 所以我删除了构造函数。