Roadmap › ASP.NET Core Web API & REST › Module: Building Robust APIs
Lessons in this course (15)

5. Middleware: built-in and custom

Intermediate★ Must knowLesson 5 of 15
csharp
public class CorrelationIdMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext ctx, ILogger<CorrelationIdMiddleware> log)
    {
        var id = ctx.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? Guid.NewGuid().ToString();
        ctx.Response.Headers["X-Correlation-Id"] = id;
        using (log.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id }))
            await next(ctx);
    }
}
app.UseMiddleware<CorrelationIdMiddleware>();

// inline
app.Use(async (ctx, next) => { /* before */ await next(ctx); /* after */ });
app.Run(async ctx => await ctx.Response.WriteAsync("terminal"));     // terminal: no next
app.Map("/health", b => b.Run(async c => await c.Response.WriteAsync("OK")));   // branch

Use can call next; Run is terminal; Map/MapWhen branch the pipeline. Order matters: e.g. UseAuthentication before UseAuthorization; CORS before auth; exception handler first.