Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Use GUID as TraceIdentifier in ASP.NET Core Web API

5.00/5 (3 votes)
22 Jul 2022CPOL 16.3K   44  
Set a generated unique id to HttpContext.TraceIdentifier using middleware

Background

HttpContext.TraceIdentifier is a unique identifier to represent a request in trace logs. Kestrel generates this ID as {ConnectionId}:{Request number} like 0HLEACIU86PT7:00000005. Now if we want to customize this process, can assign a generated unique id using middleware.

TraceIdentifier Middleware

Middleware

C#
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;

namespace Cpm.Web.Api.Middlewares
{
    public class TraceIdMiddleware
    {
        private readonly RequestDelegate _next;

        public TraceIdMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            context.TraceIdentifier = Guid.NewGuid().ToString();
            string id = context.TraceIdentifier;
            context.Response.Headers["X-Trace-Id"] = id;
            await _next(context);
        }
    }
}

Here, we are assigning Guid.NewGuid().ToString() to ccontext.TraceIdentifier and adding the value to the response header as X-Trace-Id.

Use Middleware

Let's use the filter and middleware in Startup.cs or in the bootstrap file. In void Configure(IApplicationBuilder app, IWebHostEnvironment env), add:

C#
/*Middleware*/
app.UseMiddleware<TraceIdMiddleware>();

Testing

Curl

curl -X GET "https://localhost:7178/api/Hello" -H  "accept: text/plain"

Response Headers

content-type: application/json; charset=utf-8 
date: Mon18 Jul 2022 10:25:18 GMT 
server: Kestrel 
x-trace-id: 0c635697-5606-4417-970f-6cdeebbc60ed 

Important

This middleware should be used as the first middleware in the pipeline.

Reference

History

  • 22nd July, 2022: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)