using Serilog.Context; namespace SCM.Api.Middleware; /// Garante um CorrelationId por requisição e o propaga para logs e resposta. public sealed class CorrelationIdMiddleware { public const string HeaderName = "X-Correlation-ID"; private readonly RequestDelegate _next; public CorrelationIdMiddleware(RequestDelegate next) => _next = next; public async Task InvokeAsync(HttpContext context) { var correlationId = context.Request.Headers.TryGetValue(HeaderName, out var value) && !string.IsNullOrWhiteSpace(value) ? value.ToString() : Guid.NewGuid().ToString("D"); context.Items[HeaderName] = correlationId; context.Response.OnStarting(() => { context.Response.Headers[HeaderName] = correlationId; return Task.CompletedTask; }); using (LogContext.PushProperty("CorrelationId", correlationId)) using (LogContext.PushProperty("RequestId", context.TraceIdentifier)) { await _next(context); } } }