Click here to Skip to main content
15,879,535 members
Articles / Web Development / ASP.NET
Tip/Trick

Use GUID as TraceIdentifier in ASP.NET Core Web API

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
22 Jul 2022CPOL 13.9K   44   8   2
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)


Written By
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionOpenTelemetry.NET does this for you Pin
David Killian26-Jul-22 11:56
professionalDavid Killian26-Jul-22 11:56 
AnswerRe: OpenTelemetry.NET does this for you Pin
DiponRoy27-Jul-22 19:47
DiponRoy27-Jul-22 19:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.