.NETMedium
How does middleware ordering affect request processing?
Middleware in ASP.NET Core runs as a pipeline: each component can act before the request is processed, after the response is built, or both. Order matters because each one wraps the next.
app.UseHttpsRedirection(); // 1. redirect HTTP→HTTPS first
app.UseStaticFiles(); // 2. serve files before authentication runs
app.UseRouting(); // 3. match a route
app.UseCors(); // 4. CORS — between routing and auth
app.UseAuthentication(); // 5. identify the user
app.UseAuthorization(); // 6. check policies
app.UseEndpoints(...); // 7. invoke the matched handler
Common bugs from wrong order:
UseAuthorizationbeforeUseAuthentication→ every request is anonymous, every[Authorize]returns 401.UseStaticFilesafterUseAuthentication→ static assets unnecessarily run through auth, adding latency and possibly redirecting CSS to a login page.UseCorsafterUseAuthentication→ preflight OPTIONS requests get challenged for credentials and fail.- Custom exception-handling middleware too late → exceptions from earlier middleware aren't caught.
Mental model: the pipeline is an onion. The first Use* is the outermost layer that sees the raw request first and the final response last. Authorize where the request needs gating; serve static assets before anything expensive.