目录
背景
HttpContext.TraceIdentifier是表示跟踪日志中的请求的唯一标识符。Kestrel生成此ID为{ConnectionId}:{Request number},类似0HLEACIU86PT7:00000005。现在,如果我们想自定义此过程,可以使用中间件分配生成的唯一ID。
跟踪标识符中间件
中间件
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);
}
}
}
在这里,我们将Guid.NewGuid().ToString()赋值给ccontext.TraceIdentifier并添加X-Trace-Id到响应标头中。
使用中间件
让我们在Startup.cs或引导程序文件中使用过滤器和中间件,在void Configure(IApplicationBuilder app, IWebHostEnvironment env)中,添加:
/*Middleware*/
app.UseMiddleware<TraceIdMiddleware>();
测试
Curl
curl -X GET "https://localhost:7178/api/Hello" -H "accept: text/plain"
响应标头
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
重要
此中间件应用作管道中的第一个中间件。
参考
https://www.codeproject.com/Tips/5337613/Use-GUID-as-TraceIdentifier-in-ASP-NET-Core-Web-AP