How do I get the correlationID of a request using MVC 6?
I want to use it when I log a message so that I can track a request through the system.
In previous versions I would have used the HttpRequestMessageExtensions.GetCorrelationId method: https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessageextensions.getcorrelationid%28v=vs.118%29.aspx
In ASP.NET Web API you could use message handlers to implement correlation IDs. However, in ASP.NET Core MVC 5 you don’t have message handlers. Therefore to implement correlation IDs in ASP.NET Core you must take advantage of a middleware. Create a class named CustomMiddleware in a file named CustomMiddleware.cs in your project.
if (!httpContext.Response.Headers. The CustomMiddleware class logs the correlation ID if it is found in the request header. If a correlation ID is not available in the request header, a new correlation ID is generated and added to the request and response headers. Note that a correlation ID here is a GUID — a globally unique identifier.
The GetCorrelationId () extension method first checks to see if the correlation ID is present in the request. If the correlation ID is present, the method retrieves the correlation ID from the request object and adds it to the response header. If the correlation ID is not present, it generates one and adds it to the response header.
If a correlation ID is not available in the request header, a new correlation ID is generated and added to the request and response headers. Note that a correlation ID here is a GUID — a globally unique identifier.
In the newest versions, HttpContext
directly exposes a TraceIdentifier
property you can use as a correlation identifier: https://github.com/aspnet/HttpAbstractions/blob/dev/src/Microsoft.AspNetCore.Http.Abstractions/HttpContext.cs#L72
public void MvcAction() {
var identifier = HttpContext.TraceIdentifier;
}
In older versions, you might have to use the IHttpRequestIdentifierFeature
feature to retrieve the request identifier:
public void MvcAction() {
var feature = HttpContext.Features.Get<IHttpRequestIdentifierFeature>();
var identifier = feature.TraceIdentifier;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With