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

What is middleware in ASP.NET Core, and how does the order in which it's registered affect request handling?

Short answer

Middleware are components chained together into a pipeline that every incoming HTTP request passes through before reaching application logic (and every response passes back through on the way out) -- each middleware component can inspect or modify the request/response, or…

Save .NET mock interview
Advertisement
AModel answer
Middleware are components chained together into a pipeline that every incoming HTTP request passes through before reaching application logic (and every response passes back through on the way out) -- each middleware component can inspect or modify the request/response, or short-circuit the pipeline entirely (like rejecting an unauthenticated request before it ever reaches a controller), and then calls the next delegate to continue to the next component. Registration order in Program.cs directly determines execution order, so placing authentication after authorization, for instance, would mean authorization runs against a request that hasn't been authenticated yet.
var app = builder.Build();

app.Use(async (context, next) => {
    Console.WriteLine($"Request: {context.Request.Path}");
    await next(); // passes control to the next middleware in the pipeline
});

app.UseRouting();
app.UseAuthentication(); // must run BEFORE authorization
app.UseAuthorization();
app.MapControllers();
app.Run();
Real-world example
A custom logging middleware registered first in the pipeline records every incoming request's path and timing, while authentication and authorization middleware registered afterward ensure that logging captures even requests that are ultimately rejected for being unauthenticated.
Likely follow-ups
  • What specifically goes wrong if UseAuthorization() is registered before UseAuthentication()?
  • How would you write a custom middleware that short-circuits the pipeline for a specific condition?
Related topics