| 12345678910111213141516171819202122232425262728293031323334353637 |
- namespace Diligent.WebAPI.Host.Middlewares
- {
- public class CorrelationMiddleware
- {
- private const string DefaultHeader = "X-Correlation-ID";
- private readonly RequestDelegate next;
- private readonly ILogger<CorrelationMiddleware> logger;
- public CorrelationMiddleware(RequestDelegate next, ILogger<CorrelationMiddleware> 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<string, object>
- {
- ["CorrelationId"] = correlation
- }))
- {
- context.Items.Add(DefaultHeader, correlation);
- await next(context);
-
- }
- }
- }
- }
|