CorrelationId Middleware
public class CorrelationIdMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
public CorrelationIdMiddleware(RequestDelegate next) | |
{ | |
_next = next; | |
} | |
public async Task Invoke(HttpContext context) | |
{ | |
context.Request.Headers.TryGetValue("correlation-id", out var correlationIds); | |
var correlationId = correlationIds.FirstOrDefault() ?? Guid.NewGuid().ToString(); | |
CorrelationContext.SetCorrelationId(correlationId); | |
// Serilog | |
using (LogContext.PushProperty("correlation-id", correlationId)) | |
{ | |
await _next.Invoke(context); | |
} | |
} | |
} |
public class Startup | |
{ | |
public virtual void ConfigureServices(IServiceCollection services) | |
{ | |
// Code removed for brevity | |
} | |
public void Configure(IApplicationBuilder app) | |
{ | |
// Add Middleware at start of the reqeust | |
app.UseMiddleware<CorrelationIdMiddleware>(); | |
app.UseRouting(); | |
app.UseEndpoints(endpoints => endpoints.MapControllers()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment