Middleware are components in the ASP.NET Core pipeline that process every HTTP request and response. Each one can act before calling the next component, after it returns, or end the request early. app.Use vs app.Run - app.Use((context, next) => ...) adds middleware that can call the next component. Use it when the request should continue. - app.Run(context => ...) adds terminal middleware with no next delegate. The pipeline stops there, so anything registered after it is never executed for that path. app.Use(async (ctx, next) => { ctx.Response.Headers["X-Content-Type-Options"] = "nosniff"; await next(ctx); }); app.Run(ctx => ctx.Response.WriteAsync("Fallback")); Custom middleware — yes, a typical example is a correlation ID middleware: public sealed class CorrelationIdMiddleware(RequestDelegate next) { private const string Header = "X-Correlation-ID"; public async Task InvokeAsync(HttpContext context, ILogger<CorrelationIdMiddleware> logger) { var id = context.Request.Headers.TryGetValue(Header, out var value) && !string.IsNullOrWhiteSpace(value) ? value.ToString() : context.TraceIdentifier; context.Response.OnStarting(() => { context.Response.Headers[Header] = id; return Task.CompletedTask; }); using (logger.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id })) { await next(context); } } } // Program.cs app.UseMiddleware<CorrelationIdMiddleware>(); Key details: - The class needs a constructor taking RequestDelegate and an Invoke or InvokeAsync method taking HttpContext. - Conventional middleware is created once, so scoped services (like DbContext) must be injected as InvokeAsync parameters, not in the constructor. - Register it in the right position: for example exception-handling middleware first, and anything that needs the user identity after UseAuthentication. - Use Response.OnStarting to add headers safely before the response begins. Other custom middleware I would mention: global exception handling, request logging and timing, tenant resolution, and security headers.
Ravindra Wadile · · 0 likes