使用GUID作为ASP.NET Core Web API中的跟踪标识符

目录

背景

跟踪标识符中间件

中间件

使用中间件

测试

Curl

响应标头

重要

参考


背景

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值