What's the difference between app.Use, app.Run, and app.Map in configuring the middleware pipeline?
Short answer
app.Use adds middleware that can call next() to continue the pipeline (non-terminal). app.Run adds terminal middleware that never calls next() -- it always ends the pipeline at that point.
Advertisement
AModel answer
app.Use adds middleware that can call next() to continue the pipeline (non-terminal). app.Run adds terminal middleware that never calls next() -- it always ends the pipeline at that point. app.Map (and MapWhen) branches the pipeline based on a request path or predicate, letting you build entirely separate sub-pipelines for different routes, such as a distinct branch for /admin requests.
app.Map("/admin", adminApp => {
adminApp.UseMiddleware<AdminAuthMiddleware>();
adminApp.Run(async context => await context.Response.WriteAsync("Admin area"));
});
app.Run(async context => await context.Response.WriteAsync("Main app"));Real-world example
An application branches its pipeline with app.Map("/health") to serve a lightweight health check response without running through the full authentication and logging middleware stack used by the main application routes.
Likely follow-ups
- How does MapWhen differ from Map for conditional branching?
- Can branched pipelines rejoin the main pipeline afterward?
Related topics