Search code examples
c#asp.net-coredotnet-httpclient

How to set custom DelegatingHandler to all HttpClients automatically?


I would like to use the LoggingHttpClientHandler for all the clients in the application. I found the only usable way via named/typed client

startup.cs

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

and then in each service I have to use var client = _clientFactory.CreateClient("clientWithLogging") which is kinda uncomfortable.

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

Is there a way how to do it without naming each client?


Solution

  • The problem was with resolving of params in useless constructor of LoggingHttpClientHandler. So I removed the constructor.