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
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:
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