Each HTTP request passes through a chain of middleware components—authentication, routing, static files, exception handling—before reaching your endpoint. Order matters: first registered runs first on the way in, last on the way out.
Typical pipeline order
- Exception handling / HSTS (production)
- HTTPS redirection
- Static files
- Routing
- Authentication
- Authorization
- Endpoints (controllers, minimal APIs)
app.UseExceptionHandler("/Error");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
Custom middleware sketch
app.Use(async (context, next) => {
// before
await next(context);
// after
});
Important interview questions and answers
- Q: Middleware vs filter?
A: Middleware sees all requests globally; action filters run around MVC actions only. - Q: Why UseAuthentication before UseAuthorization?
A: Authorization needs an authenticated user identity established first.
Self-check
- What runs first: routing or static files?
- Where does exception middleware usually sit?
Tip: Draw the pipeline on paper: request enters top middleware, exits bottom. UseAuthentication must precede UseAuthorization—order is dependency order, not alphabetical.
Interview prep
- Middleware vs MVC filter?
Middleware runs for every request globally; action filters wrap MVC actions only—use middleware for cross-cutting HTTP concerns like exception handling.