Advertisement
Intermediate .NET, ASP.NET Core Middleware & Request Pipeline

Why does the order in which middleware is registered matter so much in ASP.NET Core?

Short answer

Middleware executes in exactly the order it's registered for the 'incoming' phase, then unwinds in reverse order for the 'outgoing' phase -- so registering exception handling before routing means it can catch errors from routing and everything after it, but registering…

Save .NET mock interview
Advertisement
AModel answer
Middleware executes in exactly the order it's registered for the 'incoming' phase, then unwinds in reverse order for the 'outgoing' phase -- so registering exception handling before routing means it can catch errors from routing and everything after it, but registering authentication after authorization would mean requests are checked for permissions before their identity is even established, causing incorrect behavior.
app.UseExceptionHandler("/error");  // must be early to catch errors from everything after
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();  // must come before UseAuthorization
app.UseAuthorization();
app.MapControllers();
Real-world example
A team debugging why authorization checks always fail discovers UseAuthorization() was accidentally registered before UseAuthentication(), meaning no user identity was ever established before the permission check ran.
Likely follow-ups
  • What's the recommended standard middleware order for a typical web API?
  • How does UseRouting and UseEndpoints (or minimal API mapping) fit into this order?
Related topics