How to add user context to request traces in ASP.NET Core

The solution to this problem is adding metadata such as user Id or user name to enrich your traces. To achieve this, we’ll implement a middleware component in our project. Recall that, in ASP.NET Core, a middleware is a component that is capable of handling Http requests and responses by attaching itself to the request processing pipeline.

Create a middleware to capture user context

A middleware component in ASP.NET Core is represented by a class that looks like any other C# class and contains the InvokeAsync method. To implement the middleware for this example, create a new class named MyUserContextMiddleware into your project. Initially, this class should look like this:


public sealed class MyUserContextMiddleware
{
    public async Task InvokeAsync(HttpContext context)
    {
        //Not yet implemented
    }
}

In ASP.NET Core, a middleware should have a constructor that accepts a reference to an instance of a RequestDelegate type as a parameter. To be more precise, a RequestDelegate is similar to any other delegate that accepts an HttpContext and returns a Task as shown in the code snippet given below.


public class MyUserContextMiddleware
{
    private readonly RequestDelegate _next;
    public MyUserContextMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public async Task InvokeAsync(HttpContext context)
    {
        //Not yet implemented
    }
}

You can also write the above piece of code as shown below.

Donner Music, make your music with gear
Multi-Function Air Blower: Blowing, suction, extraction, and even inflation

Leave a reply

Please enter your comment!
Please enter your name here