0Pricing
C# Academy · Lesson

Middleware Ordering & Built-in Middleware

Understand correct middleware ordering for authentication, routing, CORS, and exception handling.

Why Ordering Matters

ASP.NET Core middleware runs in the exact order it is registered. Wrong order causes security holes, performance issues, or broken behavior — for example, routing must come before authorization, which must come before endpoint execution.

The Recommended Middleware Order

Microsoft documents the recommended order. Deviating from it creates hard-to-debug issues. Here is the canonical order for a production ASP.NET Core API.

// Recommended order:
app.UseExceptionHandler();    // 1. Catch all exceptions
app.UseHsts();                // 2. HTTP Strict Transport Security
app.UseHttpsRedirection();    // 3. Redirect HTTP to HTTPS
app.UseStaticFiles();         // 4. Serve static assets
app.UseRouting();             // 5. Match route patterns
app.UseCors();                // 6. Cross-Origin
app.UseAuthentication();      // 7. Who are you?
app.UseAuthorization();       // 8. Are you allowed?
app.UseRateLimiter();         // 9. Throttle
app.UseOutputCache();         // 10. Cache responses
// Map endpoints here
app.MapControllers();
app.Run();

All lessons in this course

  1. ASP.NET Core Pipeline Overview
  2. Writing Custom Middleware
  3. Short-Circuiting & Branching
  4. Middleware Ordering & Built-in Middleware
← Back to C# Academy