scm-api / src /SCM.Api /Middleware /CorrelationIdMiddleware.cs
rafaeldavila's picture
Deploy SCM API (.NET 8) - Docker Space
de8b914 verified
Raw History Blame Contribute Delete
1.1 kB
using Serilog.Context;
namespace SCM.Api.Middleware;
/// <summary>Garante um CorrelationId por requisição e o propaga para logs e resposta.</summary>
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);
}
}
}