NullReferenceException in CorrelationIdHandler
tjrobinson opened this issue · comments
I'm trying to upgrade to 3.0.0 but having some problems when using AddCorrelationIdForwarding()
(which enables the CorrelationIdHandler
in AddHttpClient
registrations).
When an HttpClient
is used, the exception is:
System.NullReferenceException: Object reference not set to an instance of an object.
at at CorrelationId.HttpClient.CorrelationIdHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
The exception is on this line: https://github.com/stevejgordon/CorrelationId/blob/master/src/CorrelationId/HttpClient/CorrelationIdHandler.cs#L22
this._correlationContextAccessor.CorrelationContext
is null.
This only happens when I'm making a request as part of the application startup code, i.e. not as part of a wider request/response. And therefore the CorrelationIdMiddleware
hasn't run, and had a chance to set up the CorrelationContext
.
I've managed to work round this by implementing my own CorrelationIdMiddleware
which adds a null check on this._correlationContextAccessor.CorrelationContext
:
if (_correlationContextAccessor.CorrelationContext != null && !request.Headers.Contains(_correlationContextAccessor.CorrelationContext.Header))
Hope this makes sense, and hopefully helps if anyone else comes across this.
Thanks for reporting this @tjrobinson. It probably makes sense to check for this. The main use was intended for it to only be added to HttpClients used during the request flow but I can see how this assumption can be problematic.
@stevejgordon could we please promote this PR ? We are also facing similar issues.
We are facing the same issue. Sometimes, an API will trigger a Hangfire job which is detached from the CorrelationContext. In that case, if the Hangfire job use this HttpClient to call some other API. It will throw NPE.
Could you @stevejgordon please promote the PR of @VKAlwaysWin ?
Thanks,
This has no been merged and I'll get a patch release out with this ASAP.
This is now available in v3.0.1. Thanks @VKAlwaysWin for the PR and my apologies for taking sooo long to get around to focusing on this!
Thank you for this update Steve, my team was having this exact same issue also . Thank you for the swift fix
Thank you @stevejgordon! This issue is gone in 3.0.1.