Home > Software engineering >  How to use message handlers in .NET 6?
How to use message handlers in .NET 6?

Time:07-19

I need to add a custom header to each http request. To do so, I want to use a message handler and override SendAsync() method like so:

    public class RequestHandler : DelegatingHandler
    {
        private readonly ICorrelationIdAccessor _correlationIdAccessor;

        public RequestHandler(ICorrelationIdAccessor correlationIdAccessor)
        {
            _correlationIdAccessor = correlationIdAccessor;
        }

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Add("CorrelationId", _correlationIdAccessor.GetCorrelationId());

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

How can I register this new message handler in Program.cs using .NET 6 ?

What I did for now, is to create a HttpConfiruration object and add the RequestHandler to the MessageHandlers collection, but I don't know how to register it to the builder:

var httpConfig = new HttpConfiguration();
httpConfig.MessageHandlers.Add(new RequestHandler());

Any suggestions on how to do this, or any other ways on how to add a custom header to all the HTTP requests are welcomed.

Thank you !

CodePudding user response:

AFAIK you can do it for named/typed HttpClient created by IHttpClientFactory (see one, two):

builder.Services.AddHttpClient<SomeServiceUsingHttpClient>()
    .AddHttpMessageHandler<RequestHandler>();

See outgoing request middleware part of the docs.

CodePudding user response:

If you also seek to add the DelegatingHandler to all of your HttpClients constructed by the IHttpClientFactory, then the following will achieve that.

builder.Services.ConfigureAll<HttpClientFactoryOptions>(options =>
    {
        options.HttpMessageHandlerBuilderActions.Add(builder =>
        {
            builder.AdditionalHandlers.Add(builder.Services.GetRequiredService<RequestHandler>());
        });
    });
builder.Services.AddScoped<RequestHandler>();

In the code snippet, all HttpClients will use the RequestHandler as a MessageHandler, and finally remember to add the RequestHandler to the ServiceCollection as well.

  • Related