What is middleware in ASP.NET Core, and how does it form the request pipeline?
Short answer
Middleware are components assembled into a pipeline that handles every incoming HTTP request and outgoing response.
Advertisement
AModel answer
Middleware are components assembled into a pipeline that handles every incoming HTTP request and outgoing response. Each middleware can perform work before and after calling the next component in the pipeline (via `next()`), or short-circuit the pipeline entirely by not calling next, letting you compose cross-cutting concerns like authentication, logging, and error handling as discrete, reusable, ordered steps.
var app = builder.Build();
app.Use(async (context, next) => {
Console.WriteLine("Before");
await next();
Console.WriteLine("After");
});
app.MapGet("/", () => "Hello World");
app.Run();Real-world example
A request logging middleware wraps the entire pipeline, recording the request path before calling next() and the response status code and elapsed time after next() returns, for every single request the app handles.
Likely follow-ups
- What's the difference between app.Use and app.Run for terminal middleware?
- How do you write middleware as a reusable class instead of an inline lambda?
Related topics