Middleware
Learn how ASP.NET Core's middleware pipeline processes every request, and how to write your own middleware.
What is Middleware?
Middleware is a component that sits in the request pipeline, able to inspect, modify, or short-circuit a request before it reaches your controller — and do the same to the response on the way back out.
The Pipeline & Order
Middleware runs in the exact order it's registered in Program.cs — this order matters enormously.
Program.cs
app.UseHttpsRedirection();app.UseAuthentication();app.UseAuthorization();app.MapControllers();Request In
↓HttpsRedirection
↓Authentication
↓Authorization
↓Controller
↓Response Out
Built-in Middleware
| Middleware | Purpose |
|---|---|
| UseHttpsRedirection | Redirects HTTP requests to HTTPS |
| UseStaticFiles | Serves files from wwwroot (images, CSS, JS) |
| UseAuthentication | Identifies who the caller is |
| UseAuthorization | Checks whether that caller is allowed to proceed |
| UseCors | Controls which origins can call your API |
Custom Middleware
You can write your own middleware for cross-cutting concerns like logging every request.
app.Use(async (context, next) =>{ Console.WriteLine($"Request: {context.Request.Method} {context.Request.Path}"); await next(); // pass control to the next middleware Console.WriteLine($"Response: {context.Response.StatusCode}");});FAQs
The pipeline short-circuits there — nothing after that middleware (including your controllers) will run for that request.
Summary
- Middleware processes every request and response in a defined order.
- Order matters — authentication must run before authorization, for example.
- Custom middleware handles cross-cutting concerns like logging.