ASP.NET Core middleware: RequestDelegate, Use/Run/Map/MapWhen/UseWhen, the recommended built-in order, short-circuiting, and writing custom middleware as a convention-based class (singleton, scoped services via InvokeAsync parameters) or as IMiddleware (resolved from DI per request).
Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.
"Middleware is how ASP.NET Core handles anything cross-cutting. Each piece is a
RequestDelegate, a function fromHttpContexttoTask, and it gets a reference to the next one. It can inspect or change the request, callnext, then inspect or change the response on the way back. If it doesn't callnext, it short-circuits: static files does that when it finds a file, and so does the CORS preflight handling.
Useadds a middleware that can callnext.Runadds a terminal one.Map("/admin", ...)creates a separate branch for that path prefix,MapWhendoes the same on any condition, andUseWhenruns a branch conditionally and then rejoins the main pipeline, which is handy for something like extra logging on/apionly. Order is everything because each registration wraps the next: the exception handler has to be first so it can catch what everything after it throws, routing has to come before authorisation so authorisation knows which endpoint and policy apply, and static files usually comes before authentication so the CSS doesn't need a cookie check.For custom middleware I write a class with a constructor taking
RequestDelegateand anInvokeAsync(HttpContext)method. The mistake I see is injecting a scoped service like aDbContextinto that constructor: convention-based middleware is created once, so thatDbContextbecomes a singleton shared across requests. Scoped services go in asInvokeAsyncparameters, or I implementIMiddleware, which is resolved from DI on every request. Middleware is for things that apply to every request; anything that depends on which endpoint or model you're dealing with belongs in a filter instead."
| Method | Calls next? | Rejoins main pipeline? | Typical use |
|---|---|---|---|
Use |
Yes (optionally) | n/a | Logging, headers, timing |
Run |
No (terminal) | n/a | Fallback response |
Map("/path", b => ...) |
Branch has its own chain | No | Separate sub-app, e.g. /health |
MapWhen(predicate, ...) |
Branch has its own chain | No | Branch by header or query |
UseWhen(predicate, ...) |
Yes | Yes | Extra middleware for a subset of requests |
Request ─► UseExceptionHandler ─► UseHsts ─► UseHttpsRedirection ─► UseStaticFiles (or MapStaticAssets)
─► UseRouting ─► UseCors ─► UseAuthentication ─► UseAuthorization ─► UseRateLimiter
─► (custom middleware) ─► Endpoints
Response flows back through the same list in reverse.
IMiddleware| Convention-based | IMiddleware |
|
|---|---|---|
| Created | Once, at pipeline build | Per request, from DI |
| Registration | app.UseMiddleware<T>() only |
services.AddScoped<T>() + app.UseMiddleware<T>() |
| Scoped dependencies | InvokeAsync parameters |
Constructor |
| Strong typing | Method found by convention | Interface |
A correlation-id middleware placed first in the pipeline adds one header read and one BeginScope per request, costing microseconds, yet it turned a 40-minute log search during an incident into a single query on the id the customer quoted from the error page.
Checks that the candidate understands the pipeline mechanics and can write middleware that is safe under concurrency.
Green flags
next, short-circuiting and in/out order.Use, Run, Map and UseWhen.Red flags
DbContext into a middleware constructor.public delegate Task RequestDelegate(HttpContext context);
IApplicationBuilder.Use takes a Func<RequestDelegate, RequestDelegate>: given the next delegate, return a new one that wraps it. When the app starts, the builder folds the list from the end, so the first registered middleware becomes the outermost function.
build: endpoint ← wrap(authz) ← wrap(authn) ← wrap(routing) ← wrap(exception handler)
run: exception handler( routing( authn( authz( endpoint ))))
If a middleware returns without calling next, nothing after it runs. Examples in the framework: StaticFileMiddleware (file found), CorsMiddleware for preflight OPTIONS, HttpsRedirectionMiddleware (sends a 307/308). In .NET 8+, endpoints can call .ShortCircuit() so routing executes them immediately without running the rest of the middleware.
Map strips the matched prefix from Request.Path and moves it to PathBase inside the branch.MapWhen evaluates a predicate per request.UseWhen builds a sub-pipeline whose last step calls back into the main pipeline.UseMiddleware<T>() uses reflection once to find a public Invoke or InvokeAsync method returning Task whose first parameter is HttpContext. The instance is created once with constructor injection from the root provider. Extra InvokeAsync parameters are resolved from HttpContext.RequestServices on each call, which is how you get scoped services safely.
IMiddleware internalsIf T implements IMiddleware, UseMiddleware<T>() instead uses IMiddlewareFactory to resolve T from the request's scope on each request and releases it afterwards. That costs a DI resolution per request but gives a normal constructor and a lifetime you choose.
After await next(context) the response may already have started. To add headers on the way out, register context.Response.OnStarting(() => { ... }) before calling next.
app.Use lambdas that log "before" and "after"; confirm the nesting order.IMiddleware and register it as scoped.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"), ...) to add a header only to API responses.await next on a large response and observe the InvalidOperationException; fix it with OnStarting.A convention-based correlation-id middleware, a convention-based middleware taking a scoped service per call, and an IMiddleware alternative.
// CorrelationIdMiddleware.cs
namespace Shop.Api.Middleware;
// Convention-based: created ONCE, so only singleton-safe dependencies in the constructor
public sealed class CorrelationIdMiddleware(RequestDelegate next, ILogger<CorrelationIdMiddleware> logger)
{
private const string Header = "X-Correlation-Id";
public async Task InvokeAsync(HttpContext context)
{
var id = context.Request.Headers[Header].FirstOrDefault() ?? context.TraceIdentifier;
// Headers must be set before the response starts
context.Response.OnStarting(() =>
{
context.Response.Headers[Header] = id;
return Task.CompletedTask;
});
using (logger.BeginScope(new Dictionary<string, object> { ["CorrelationId"] = id }))
{
await next(context); // always awaited
}
}
}
// Convention-based with a SCOPED dependency: extra InvokeAsync parameters are resolved
// from HttpContext.RequestServices on every request, so each request gets its own instance
public sealed class RequestQuotaMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context, IQuotaStore quota) // scoped, per request
{
if (!await quota.TryConsumeAsync(context.User.Identity?.Name ?? "anon", context.RequestAborted))
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
return; // short-circuit: nothing after this middleware runs
}
await next(context);
}
}
// IMiddleware: resolved from DI per request, so scoped dependencies are fine in the constructor
public sealed class TenantAuditMiddleware(IAuditStore audit) : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
await next(context);
await audit.RecordAsync(context.Request.Path, context.Response.StatusCode, context.RequestAborted);
}
}
public interface IAuditStore { Task RecordAsync(string path, int status, CancellationToken ct); }
public interface IQuotaStore { Task<bool> TryConsumeAsync(string key, CancellationToken ct); }
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IAuditStore, SqlAuditStore>();
builder.Services.AddScoped<IQuotaStore, SqlQuotaStore>();
builder.Services.AddScoped<TenantAuditMiddleware>(); // IMiddleware must be registered
var app = builder.Build();
app.UseExceptionHandler("/error");
app.UseMiddleware<CorrelationIdMiddleware>(); // early, so every log line has the id
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<RequestQuotaMiddleware>();
app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/api"),
branch => branch.UseMiddleware<TenantAuditMiddleware>()); // only API calls are audited, then rejoins
app.MapGet("/api/orders", () => TypedResults.Ok(Array.Empty<string>()));
app.Run();
DbContext) into a convention-based middleware constructor. Why it is wrong: The middleware is created once, so one DbContext is shared across concurrent requests. Instead: Add it as an InvokeAsync parameter or implement IMiddleware.next(context) without awaiting it (or returning Task.CompletedTask after starting it). Why it is wrong: Your middleware finishes while downstream code is still running, so 'after' logic runs too early, scopes are disposed under the endpoint, and exceptions go unobserved. Instead: Always await next(context).UseExceptionHandler late in the pipeline. Why it is wrong: It only catches exceptions thrown by middleware registered after it. Instead: Register it first.Run where Use was intended. Why it is wrong: Run is terminal; nothing after it executes, including your endpoints. Instead: Use Use and call next.next. Why it is wrong: The next component may try to set headers or status after the body started, causing exceptions or corrupted responses. Instead: Either short-circuit or call next, not both.IMiddleware type in DI. Why it is wrong: UseMiddleware<T> throws at runtime because the factory cannot resolve it. Instead: services.AddScoped<T>() or AddTransient<T>().Middleware is the right tool for concerns that are true for every request regardless of endpoint: correlation ids, security headers, exception handling, request logging. A senior also knows what the framework already gives you, so you don't write your own CORS, rate limiting, response compression or exception handling middleware. When a concern depends on the endpoint, read endpoint metadata after routing (context.GetEndpoint()?.Metadata.GetMetadata<T>()) or use filters.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Inline app.Use lambda |
Tiny, app-specific behaviour | Hard to test and reuse | Anything over ~10 lines |
| Convention-based class | Reusable, hot path | Constructor dependencies must be singleton-safe | Needs scoped services in many places |
IMiddleware |
Scoped dependencies, clearer typing | DI resolution per request | Extremely hot paths |
| Endpoint/MVC filter | Depends on the endpoint or its arguments | Only runs for matched endpoints | Must run for static files or 404s |
Chain of Responsibility sends a request along a chain of handlers; each one decides whether to handle it, pass it on, or both, and the sender doesn't know which one acted.
next. ASP.NET Core middleware (RequestDelegate next) and DelegatingHandler in HttpClient work this way.Short-circuiting means returning without calling next: authentication returning 401, static files serving a file, a cache hit. That's why order matters: exception handling must wrap everything, and authentication must run before authorisation.
The trade-off is decoupling and composability against long implicit chains whose order lives far from the handlers.
Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).
.NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.
The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().
The trade-off is that order matters and long chains are harder to debug.
Last updated 23 Nov 2026.