2026-01-22 19:06:58 +08:00
|
|
|
using Serilog.Context;
|
|
|
|
|
|
|
|
|
|
namespace WebApi.Middleware;
|
|
|
|
|
|
|
|
|
|
public class RequestIdMiddleware
|
|
|
|
|
{
|
|
|
|
|
private readonly RequestDelegate _next;
|
|
|
|
|
|
|
|
|
|
public RequestIdMiddleware(RequestDelegate next)
|
|
|
|
|
{
|
|
|
|
|
_next = next;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
|
|
|
{
|
|
|
|
|
var requestId = context.Request.Headers["X-Request-ID"].FirstOrDefault() ?? Guid.NewGuid().ToString("N");
|
2026-01-30 10:41:19 +08:00
|
|
|
|
2026-01-22 19:06:58 +08:00
|
|
|
context.Items["RequestId"] = requestId;
|
2026-01-30 10:41:19 +08:00
|
|
|
|
2026-01-22 19:06:58 +08:00
|
|
|
using (LogContext.PushProperty("RequestId", requestId))
|
|
|
|
|
{
|
|
|
|
|
await _next(context);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static class RequestIdExtensions
|
|
|
|
|
{
|
|
|
|
|
public static string? GetRequestId(this HttpContext context)
|
|
|
|
|
{
|
|
|
|
|
return context.Items["RequestId"] as string;
|
|
|
|
|
}
|
2026-01-30 10:41:19 +08:00
|
|
|
|
2026-01-22 19:06:58 +08:00
|
|
|
public static IApplicationBuilder UseRequestId(this IApplicationBuilder builder)
|
|
|
|
|
{
|
|
|
|
|
return builder.UseMiddleware<RequestIdMiddleware>();
|
|
|
|
|
}
|
|
|
|
|
}
|