I created the following messagehandler to add the correlation id to an outgoing HTTP request:
public class AddCorrelationIdToRequestHandler : DelegatingHandler | |
{ | |
private const string CorrelationIdHeaderName = "X-Correlation-Id"; | |
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
request.Headers.Add(CorrelationIdHeaderName, CorrelationContainer.GetCorrelationId().ToString()); | |
return base.SendAsync(request, cancellationToken); | |
} | |
} |
and used the following code to link it to the HttpClient:
var addCorrelationIdhandler = new AddCorrelationIdToRequestHandler(); | |
var client = new HttpClient(addCorrelationIdhandler); |
Looked OK to me until I tried to execute this code. This failed horribly with the following error message:
"message": "An error has occurred.",
"exceptionMessage": "The inner handler has not been assigned.",
"exceptionType": "System.InvalidOperationException",
"stackTrace": " at System.Net.Http.DelegatingHandler.SetOperationStarted()
at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at CorrelationId.AddCorrelationIdToRequestHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
What was not obvious to me is that you have to specify the next handler in the request pipeline. As I only had one handler added, I had to specify the HttpClientHandler as the next (and final) handler:
var addCorrelationIdhandler = new AddCorrelationIdToRequestHandler() | |
{ | |
InnerHandler = new HttpClientHandler() | |
}; | |
var client = new HttpClient(addCorrelationIdhandler); |