Get traceId from ValidationProblem in ASPNet Core 3.1 Api Controller

3.8k views Asked by At

I am using Refit on my Xamarin client app. When I call my Api and there are ModelState/Validation errors I return a ValidationProblem(ModelState) to my client. Refit then throws a ValidationApiException. In the exception there is a traceId.

How can I get the traceId on the server side so I can log it? I would like to be able to correlate client device logs with the server when there are bugs/problems.

1

There are 1 answers

0
Kirk Larkin On BEST ANSWER

The source shows that the traceId property is retrieved like this:

var traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;

If you want to get hold of this inside a controller, you can use this like so:

public IActionResult MyAction()
{
    // using System.Diagnostics for Activity
    var traceId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier;

    // ...
}

Note that httpContext changed to HttpContext, which is a property of ControllerBase. If you want to access this outside of a controller, you might need to use IHttpContextAccessor instead.