.NET › ASP.NET Core Middleware & Request Pipeline
How do you conditionally apply middleware only to certain requests using UseWhen or MapWhen?
IntermediateAnswer
UseWhen(predicate, configuration) branches the pipeline conditionally based on a predicate evaluated per request, applying the given middleware chain only when the condition is true, then automatically rejoining the main pipeline afterward -- unlike Map/MapWhen, which create a fully separate branch that typically doesn't rejoin. This is useful for applying middleware (like extra logging) only to specific request types without duplicating the entire remaining pipeline.
app.UseWhen(
context => context.Request.Path.StartsWithSegments("/api"),
apiApp => apiApp.UseMiddleware<ApiKeyValidationMiddleware>()
);
// Non-API requests skip ApiKeyValidationMiddleware entirely, but both paths
// continue through the same remaining pipeline afterwardReal-world example An application applies API-key validation middleware only to requests under /api using UseWhen, while static file requests and health check endpoints skip that check entirely without needing a completely separate pipeline branch.