使用. net core 2.1.X 和 2.2.X 运行时,如果在中间件 (Middleware)修改了 HttpContext .TraceIdentifier 了,有可能后面通过 IHttpContextAccessor.HttpContext 返回为空,解决方法
public class CorrelationIdMiddleware { private readonly RequestDelegate _next; private readonly IHttpContextAccessor _httpAccessor; public CorrelationIdMiddleware(RequestDelegate next, IHttpContextAccessor httpAccessor) { _next = next; _httpAccessor = httpAccessor; } public async Task InvokeAsync(HttpContext context) { if (context.Request.Headers.ContainsKey("X-Correlation-ID")) { context.TraceIdentifier = context.Request.Headers["X-Correlation-ID"]; // WORKAROUND: On ASP.NET Core 2.2.1 we need to re-store in AsyncLocal the new TraceId, HttpContext Pair _httpAccessor.HttpContext = context; } // Call the next delegate/middleware in the pipeline await _next(context); } }
评论列表,共 0 条评论
暂无评论