Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the CorrelationID in MVC 6

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

like image 827
pac w Avatar asked Oct 21 '15 08:10

pac w


People also ask

How to implement correlation IDs in MVC 5?

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.

How do I find the correlation ID in custommiddleware?

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.

How do I get the correlation ID from a request object?

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.

What if a correlation ID is not available in the 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.


1 Answers

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;
}
like image 197
Kévin Chalet Avatar answered Sep 29 '22 19:09

Kévin Chalet