namespace Diligent.WebAPI.Host.Middlewares { public class CorrelationMiddleware { private const string DefaultHeader = "X-Correlation-ID"; private readonly RequestDelegate next; private readonly ILogger logger; public CorrelationMiddleware(RequestDelegate next, ILogger logger) => (this.next,this.logger) = (next,logger); public async Task Invoke(HttpContext context) { if (!context.Request.Headers.TryGetValue(DefaultHeader, out var correlation)) { correlation = Guid.NewGuid().ToString(); } context.Response.OnStarting(() => { if (!context.Response.Headers.ContainsKey(DefaultHeader)) { context.Response.Headers.Add(DefaultHeader, correlation); } return Task.CompletedTask; }); using (logger.BeginScope(new Dictionary { ["CorrelationId"] = correlation })) { context.Items.Add(DefaultHeader, correlation); await next(context); } } } }