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 !