Add request id to all core MVC REST API response

less than 1 minute read ~

In REST API, most of the time we only send request ID when the calls fails with 4XXX or 5XXX status codes. But it is a good practice to send the request ID with every response. This can be useful for debugging issues where successful response doesn’t produce the expected result from the backend service.

If you are using, then we can implement this by using Filters. At first create a ActivityIdHeaderResultFilter.cs file with the content -

public class ActivityIdHeaderResultFilter
    : IResultFilter
    public void OnResultExecuting(ResultExecutingContext context)
            .Add("X-ActivityId", Activity.Current?.Id);

    public void OnResultExecuted(ResultExecutedContext context)

Now Register the filter in your program.cs or startup.cs file -

services.AddMvcCore((options) =>
        // existing code omitted for brevity

Now in every request the backend service will response with X-ActivityId header with the request ID to the caller.

Leave a Comment