Navigation
Recherche
|
How to add user context to request traces in ASP.NET Core
jeudi 22 mai 2025, 11:00 , par InfoWorld
When working with web applications, you will often want to keep watch on user requests to understand user behavior. Known as request tracing, this process also enables you to monitor the reliability of your applications and to inspect requests and detect and fix errors that may occur at runtime.
In a previous article, I discussed how we can log request metadata in ASP.NET Core applications. This article dives deeper into request tracing, discusses the importance of including user context in request metadata, and shows how we can do so using custom middleware in ASP.NET Core applications. Create an ASP.NET Core Web API project in Visual Studio 2022 To create an ASP.NET Core Web API project in Visual Studio 2022, follow the steps outlined below. Launch the Visual Studio 2022 IDE. Click on “Create new project.” In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed. Click Next. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences. Click Next. In the “Additional Information” window shown next, select “.NET 8.0 (Long Term Support)” as the framework version and check the “Use controllers” check box. We’ll be using controllers in this project. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable OpenAPI Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here. Click Create. We’ll use this ASP.NET Core Web API project to work with request tracing in the sections that follow. Add user context to Http requests in ASP.NET Core When your application is experiencing runtime errors, or not working the way that it should, you will want to search your logs to understand what went wrong. However, it would be cumbersome to search through hundreds of thousands of log entries for a specific error. It would be much easier to filter the log entries using user Id to get the log entries that are relevant. However, the traditional logs for ASP.NET Core will not capture the user Id that triggered a particular request unless you add it to the logs explicitly. This becomes a problem in distributed applications, because the support teams are not able to decipher user-specific issues from the generated logs. 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. public class MyUserContextMiddleware(RequestDelegate next) { public async Task InvokeAsync(HttpContext context) { //Not yet implemented } } The InvokeAsync method accepts a reference to the HttpContext as a parameter and checks if the current user is authenticated. The user Id is retrieved from the claims of the authenticated user using the following statement. string? userId = context.User?.FindFirstValue(claimType); If a user Id is available, we use the SetTag method of the Activity.Current instance to add the tag as shown in the code snippet given below. activity.SetTag('UserId', userId); If no valid user Id is available, i.e., if the source of the request is anonymous, the request processing continues by invoking the next middleware in the request processing pipeline using the following statement. await next(context); Complete source code for MyUserContextMiddleware The complete source code of the MyUserContextMiddleware class is given below for your reference. public sealed class MyUserContextMiddleware(RequestDelegate next) { const string claimType = ClaimTypes.NameIdentifier; public async Task InvokeAsync(HttpContext context) { var activity = Activity.Current; string? userId = context.User?.FindFirstValue(claimType); var isAuthenticated = context.User?.Identity?.IsAuthenticated; if (userId == null) { await next(context); } else if (activity!= null && isAuthenticated == true) { activity.SetTag('UserId', userId); } } } Add the middleware to the request processing pipeline To be able to use the middleware, you should add it to the request processing pipeline using the following piece of code in the Program.cs file. app.UseMiddleware(); Remember to add the middleware after you’ve added the authentication and authorization middleware so that you can get the user identity information as shown in the code snippet given below. app.UseAuthentication(); app.UseAuthorization(); app.UseMiddleware(); app.MapControllers(); app.Run(); Attach additional information using the user context If you’re using a multi-tenant application, you can attach the tenant Id using the SetTag method. You can also take advantage of user context to add feature flags to enable or disable features in your application. The following code snippet shows how this can be achieved. string? tenantId = context.User?.FindFirstValue('TenantId'); var activity = Activity.Current; string? userId = context.User?.FindFirstValue(claimType); var isAuthenticated = context.User?.Identity?.IsAuthenticated; if (userId == null) { await next(context); } else if (activity!= null && isAuthenticated == true) { activity.SetTag('UserId', userId); activity.SetTag('tenantId', tenantId); activity.SetTag('MyApp.Feature-ABC', 'enabled'); } Takeaways By adding user context to your request traces in ASP.NET Core applications, you can enhance the observability of your application and facilitate faster debugging. Having the user context makes it easier to identify the root causes of errors and any other issues (i.e., slow requests, unnecessary server hits, etc.) that may occur at run time. Additionally, you can seamlessly integrate your request tracing technique with modern observability platforms such as Jaeger and Application Insights in Azure Monitor.
https://www.infoworld.com/article/3988231/how-to-add-user-context-to-request-traces-in-asp-net-core....
Voir aussi |
56 sources (32 en français)
Date Actuelle
jeu. 22 mai - 21:53 CEST
|