The ASP.NET Core pipeline
The middleware pipeline: why order matters
Each middleware can see, change, stop or pass the request on.
Understand the concept
In ASP.NET Core a request passes through middleware components arranged in order. Each receives a ‘next’ delegate: it can do its work and pass the request on, or produce the response itself and short-circuit the pipeline. On the way back the same middleware runs again in reverse order, so one middleware can see both before and after (for example to measure duration).
Order defines behaviour. The exception handler must come first so it can catch exceptions thrown by everything after it. Routing comes before authentication and authorization because authorization must read the selected endpoint’s [Authorize] metadata. Authentication precedes authorization because you cannot decide what is allowed without knowing who is asking.
Wrong order is often a silent bug: if UseAuthorization is written before UseAuthentication, every user looks anonymous and protected endpoints return 401; endpoint-specific rate limit policies registered before routing are not applied. The simulator’s ‘Unauthorised request’ scenario shows step by step why this order works.
Security, error handling and performance features only work in the right order.
Writing UseAuthorization before UseAuthentication or placing the exception handler at the end.
A letter’s journey through the city
Think of a request as a letter and the server as a city. Pick a scenario, press play and watch which gates the letter passes and where it gets stopped.
Someone asks for admin messages without signing in.
One topic. Three levels of depth.
app.UseExceptionHandler();
app.UseRouting();
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();The core order used in this project.
This page connects to no real server or database. Code samples are illustrative for .NET 8, Next.js and SQL Server; timings are example values in the simulation, not measurements. Try samples only in your own development environment; never share real connection strings, tokens or passwords.
Try it yourself first.
A developer moved app.UseExceptionHandler() below MapControllers() while debugging. How does an exception thrown in a controller behave now?
Show the solution and explanation
Hata yakalayıcı artık controller’dan önce çalışmadığı için istisnayı sarmalamaz.
İstisna sunucunun varsayılan davranışına düşer: biçimsiz bir 500,
geliştirme ortamında ise yığın izi içeren bir sayfa.A middleware can only wrap what is added after it. The exception handler must come first to be useful.