UseWhen and MapWhen are conditional middleware branching methods in .NET Core.
They both execute middleware based on condition, but there is one important difference:
-
UseWhen → Returns back to main pipeline ✅
-
MapWhen → Does NOT return to main pipeline ❌
Think of them like:
-
UseWhen → Temporary detour → come back 🚗
-
MapWhen → Permanent detour → don't come back 🚧
1. UseWhen — Returns to Main Pipeline
UseWhen executes middleware only when condition is true, and then returns back to main pipeline.
Example
app.UseWhen(context => context.Request.Path.StartsWithSegments("/admin"), appBuilder =>
{
appBuilder.Use(async (context, next) =>
{
Console.WriteLine("Admin Middleware");
await next();
});
});
app.Run(async context =>
{
await context.Response.WriteAsync("Main Pipeline");
});
If request is:
/admin
Output
Admin Middleware
Main Pipeline
👉 Notice: It comes back to main pipeline
2. MapWhen — Does NOT Return to Main Pipeline
MapWhen creates a separate branch and does not return.
Example
app.MapWhen(context => context.Request.Path.StartsWithSegments("/admin"), appBuilder =>
{
appBuilder.Run(async context =>
{
await context.Response.WriteAsync("Admin Pipeline");
});
});
app.Run(async context =>
{
await context.Response.WriteAsync("Main Pipeline");
});
If request is:
/admin
Output
Admin Pipeline
👉 Main pipeline will NOT execute
Visual Difference
UseWhen
Request
↓
Condition True
↓
Branch Middleware
↓
Back to Main Pipeline
↓
Response
MapWhen
Request
↓
Condition True
↓
Branch Middleware
↓
Response (Stops here)
Interview Comparison Table
| Feature | UseWhen | MapWhen |
|---|---|---|
| Conditional execution | ✅ Yes | ✅ Yes |
| Returns to main pipeline | ✅ Yes | ❌ No |
| Creates separate branch | ⚠️ Partial | ✅ Yes |
| Stops pipeline | ❌ No | ✅ Yes |
| Common usage | Logging, validation | Separate pipelines |
When to Use Which?
UseWhen (Common)
Use for:
-
Logging
-
Authentication checks
-
Performance tracking
-
Header validation
Example:
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), api =>
{
api.UseMiddleware<ApiLoggingMiddleware>();
});
MapWhen (Less Common)
Use for:
-
Completely separate pipelines
-
Admin panel middleware
-
Multi-tenant applications
Example:
app.MapWhen(context => context.Request.Host.Value.Contains("admin"), admin =>
{
admin.UseAuthentication();
admin.UseAuthorization();
});
Interview One-Line Answer
UseWhen executes conditional middleware and returns to main pipeline, while MapWhen creates a separate pipeline and does not return.
