Skip to content

Instantly share code, notes, and snippets.

@ankitvijay
Last active November 23, 2020 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankitvijay/31a0294e2b18ec2a7abedf4d9bb738b5 to your computer and use it in GitHub Desktop.
Save ankitvijay/31a0294e2b18ec2a7abedf4d9bb738b5 to your computer and use it in GitHub Desktop.
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