Wednesday, June 18, 2025
HomeCloud ComputingHow one can add consumer context to request traces in ASP.NET Core

How one can add consumer context to request traces in ASP.NET Core

The answer to this downside is including metadata resembling consumer Id or consumer identify to counterpoint your traces. To attain this, we’ll implement a middleware part in our undertaking. Recall that, in ASP.NET Core, a middleware is a part that’s able to dealing with Http requests and responses by attaching itself to the request processing pipeline.

Create a middleware to seize consumer context

A middleware part in ASP.NET Core is represented by a category that appears like some other C# class and accommodates the InvokeAsync technique. To implement the middleware for this instance, create a brand new class named MyUserContextMiddleware into your undertaking. Initially, this class ought to appear to be this:


public sealed class MyUserContextMiddleware
{
    public async Activity InvokeAsync(HttpContext context)
    {
        //Not but carried out
    }
}

In ASP.NET Core, a middleware ought to have a constructor that accepts a reference to an occasion of a RequestDelegate sort as a parameter. To be extra exact, a RequestDelegate is much like some other delegate that accepts an HttpContext and returns a Activity as proven within the code snippet given under.


public class MyUserContextMiddleware
{
    non-public readonly RequestDelegate _next;
    public MyUserContextMiddleware(RequestDelegate subsequent)
    {
        _next = subsequent;
    }
    public async Activity InvokeAsync(HttpContext context)
    {
        //Not but carried out
    }
}

You too can write the above piece of code as proven under.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments