.NET › ASP.NET Core Middleware & Request Pipeline

How do you conditionally apply middleware only to certain requests using UseWhen or MapWhen?

Intermediate

Answer

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 afterward
Real-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.

Common follow-ups: How does UseWhen's rejoining behavior differ from Map's branching?;What's a good use case for MapWhen instead of UseWhen?