The middleware pipeline
Middleware is the chain of components every request passes through. This lesson shows how the chain is built, why the order matters so much, and how to write your own middleware class.
- StartRequest arrivesKestrel hands the HttpContext to the first middleware
- Step 2Exception handlerCatches errors from everything after it
- Step 3HTTPS redirectionRedirects http:// requests to https://
- Step 4Static filesReturns CSS, JS and images directly and stops the pipeline
- Step 5RoutingWorks out which endpoint matches the URL
- Step 6AuthenticationReads the cookie or token and sets the user
- Step 7AuthorizationChecks the user may access the endpoint
- EndEndpointThe controller action runs and the response heads back out
Each middleware can work before and after the next one, or stop the request early.
The idea in plain words
A middleware is a small piece of code that receives the HttpContext and a reference to the next middleware. It can do something, call the next one, and then do something else when the next one returns. Because each middleware wraps the ones after it, the order you add them in Program.cs is the order requests flow through.
Some middleware short-circuits the pipeline. The static files middleware, for example, writes the file to the response and never calls the next middleware, so your controllers are not involved at all.
- app.Use adds middleware that can call the next one.
- app.Run adds terminal middleware; nothing after it runs.
- app.Map branches the pipeline for a path prefix.
Example: a custom middleware class
Middleware classes take a RequestDelegate in the constructor and expose an InvokeAsync method. This one adds a header with the request id to every response. Headers are set before calling next, because once the response body starts they can no longer change.
public class RequestIdMiddleware
{
private readonly RequestDelegate _next;
public RequestIdMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
context.Response.Headers["X-Request-Id"] = context.TraceIdentifier;
await _next(context);
}
}
// Program.cs, after builder.Build()
app.UseMiddleware<RequestIdMiddleware>();Common mistakes
Most middleware bugs are ordering bugs.
- Calling UseAuthentication after UseAuthorization, so the user is unknown when access is checked.
- Putting UseStaticFiles after authorization by accident, which makes every image require a login.
- Writing to the response after calling next when the response has already started.
- Doing slow synchronous work in middleware that runs for every request.
Interview question
What is the difference between middleware and MVC filters?
Middleware runs for every request in the app pipeline and only knows about the HttpContext. Filters run inside MVC, only for controller actions, and have access to MVC details such as the action, its arguments, model state and the result. Use middleware for cross-cutting concerns like logging, headers or exception handling for all requests, and filters for concerns tied to actions, such as validation or per-action caching.
Want the full details? Read the official Microsoft documentation for this topic.