Last active
November 23, 2020 20:41
-
-
Save ankitvijay/31a0294e2b18ec2a7abedf4d9bb738b5 to your computer and use it in GitHub Desktop.
CorrelationId Middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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