-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCorrelationIdMiddleware.cs
More file actions
37 lines (31 loc) · 1.02 KB
/
CorrelationIdMiddleware.cs
File metadata and controls
37 lines (31 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System.Diagnostics;
using Serilog.Context;
public class CorrelationIdMiddleware
{
private readonly RequestDelegate _next;
public CorrelationIdMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var correlationId = context.Request.Headers["X-Correlation-ID"].FirstOrDefault() ?? Activity.Current?.Id ?? Guid.NewGuid().ToString();
context.Items["CorrelationId"] = correlationId;
using (LogContext.PushProperty("CorrelationId", correlationId))
{
context.Response.OnStarting(() =>
{
context.Response.Headers.Append("X-Correlation-ID", correlationId);
return Task.CompletedTask;
});
await _next(context);
}
}
}
public static class CorrelationIdMiddlewareExtensions
{
public static IApplicationBuilder UseCorrelationId(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CorrelationIdMiddleware>();
}
}