skip to content

In ASP.NET Core, how do app.Map, app.MapWhen and app.UseWhen branch the middleware pipeline, and which one rejoins the main pipeline?

level: middleimportance: should knowfreq 50%

answer

  1. branch on path vs predicate
  2. Map matches whole segments
  3. MapWhen takes Func<HttpContext, bool>
  4. UseWhen appends main as the branch's next
  5. a dead-end branch answers 404

basics

~20 s

Map branches on a path prefix and MapWhen on a Func<HttpContext, bool>; both hand the request to a separate pipeline that never returns to the main one. UseWhen also branches on a predicate but rejoins the main pipeline unless the branch short-circuits.

solid answer

~40 s

`app.Map("/kiosk", branch => ...)` checks `Request.Path.StartsWithSegments`, so it matches `/kiosk` and `/kiosk/7` but not `/kiosks`; matching requests run the branch pipeline only, with the matched segment moved from `Path` to `PathBase`. `app.MapWhen(predicate, branch => ...)` does the same on any `Func<HttpContext, bool>` and leaves the path alone. Neither returns to the main pipeline: if the branch has no terminal middleware and nobody answers, the branch's own end sets 404. `app.UseWhen(predicate, branch => ...)` builds the branch with the rest of the main pipeline appended as its final step, so the request continues to routing and endpoints after the branch, unless a branch middleware short-circuits. Use `UseWhen` for conditional extra middleware, `Map` or `MapWhen` for a separate mini-app.

code

csharp · 15 lines
csharp
// Extra middleware for kiosk calls, then the normal pipeline
app.UseWhen(ctx => ctx.Request.Headers.ContainsKey("X-Kiosk-Id"), kiosk =>
    kiosk.Use(async (ctx, next) =>
    {
        ctx.Response.Headers["X-Kiosk-Seen"] = "1";
        await next(ctx);
    }));

// Separate mini-pipeline chosen by predicate; never rejoins
app.MapWhen(ctx => ctx.Request.Query.ContainsKey("v1"), legacy =>
    legacy.Run(ctx => ctx.Response.WriteAsync("Legacy guide")));

// Separate mini-pipeline for /diagnostics and below; never rejoins
app.Map("/diagnostics", diag =>
    diag.Run(ctx => ctx.Response.WriteAsync("ok")));

go deeper

for a junior

Know that Map branches on a path and that UseWhen runs extra middleware before carrying on with the normal pipeline.

for a middle

Explain segment-aware matching, the 404 at the end of a dead-end branch, and how UseWhen appends the main pipeline to its branch.

for a senior

Choose between a branch, a route group and endpoint metadata, and spot middleware that silently stops running for branched requests.

for a principal

Judge when branching a single host into mini-apps beats splitting them into separately deployed services, and how that affects operability.

## Three ways to branch ASP.NET Core's `IApplicationBuilder` offers three extension methods that split the pipeline. Each creates a **new builder** (`app.New()`), lets you configure it, and inserts a small piece of middleware into the main pipeline that decides per request whether to enter the branch. | Method | Condition | Path changes | After the branch | |---|---|---|---| | `Map(pathMatch, configure)` | `Request.Path` starts with whole segments of `pathMatch` | matched segment moves to `PathBase` | never returns to the main pipeline | | `MapWhen(predicate, configure)` | any `Func<HttpContext, bool>` | none | never returns to the main pipeline | | `UseWhen(predicate, configure)` | any `Func<HttpContext, bool>` | none | continues into the main pipeline | ## Map and MapWhen: separate mini-pipelines `Map` adds `MapMiddleware`. For each request it calls `Request.Path.StartsWithSegments(pathMatch, ...)`. That comparison is **segment-aware** and case-insensitive: `/diagnostics` matches `/diagnostics` and `/Diagnostics/db`, but not `/diagnosticsx`. When it matches, the branch delegate runs **instead of** the main pipeline's next component. The path you pass may not end with `/`; `Map` throws an `ArgumentException` at startup if it does. `MapWhen` adds `MapWhenMiddleware`, which evaluates your predicate and, if it returns true, runs the branch instead of the rest of the main pipeline. It does not touch `Path` or `PathBase`. Because a branch is built by its own `Build()` call, it gets its own built-in end delegate. A branch whose middleware all call `next` therefore ends in that delegate, which sets **404**: the request does **not** fall back to the main pipeline. Give every `Map` or `MapWhen` branch a terminal `Run` or something that answers. ## UseWhen: conditional middleware that rejoins `UseWhen` is the one to reach for when you want extra middleware for *some* requests and then normal processing. Its implementation builds the branch lazily, when the main pipeline is built: it calls `branchBuilder.Run(main)`, appending the rest of the main pipeline as the branch's terminal step. So: 1. The predicate is evaluated per request. 2. If true, the request runs the branch's middleware, then continues with the rest of the main pipeline. 3. If false, the request goes straight to the rest of the main pipeline. 4. A branch middleware that does not call `next` still short-circuits everything, main pipeline included. ## The museum audio-guide API The audio-guide API logs extra detail for gallery kiosks, keeps a legacy v1 endpoint for old handsets, and exposes a diagnostics page: ```csharp app.UseWhen(ctx => ctx.Request.Headers.ContainsKey("X-Kiosk-Id"), kiosk => kiosk.Use(async (ctx, next) => { app.Logger.LogInformation("Kiosk {Id}", ctx.Request.Headers["X-Kiosk-Id"].ToString()); await next(ctx); // continues into the main pipeline })); app.MapWhen(ctx => ctx.Request.Query.ContainsKey("v1"), legacy => legacy.Run(ctx => ctx.Response.WriteAsync("Legacy guide"))); app.Map("/diagnostics", diag => diag.Run(ctx => ctx.Response.WriteAsync("ok"))); ``` Kiosk requests still reach routing and the tour endpoints. Requests with `?v1` never do, and neither does anything under `/diagnostics`. ## Choosing between them The three methods answer different needs, and picking the wrong one produces bugs that look like routing problems: - **Conditional cross-cutting work** (extra logging for kiosks, a header for one tenant, request buffering for one upload path): `UseWhen`. The request must still reach the normal endpoints. - **A self-contained mini-app under a prefix** (a diagnostics page, an embedded documentation site, a legacy protocol handler): `Map`. The path rewrite lets it be written as if it lived at the root. - **A separate mini-app chosen by something other than the path** (a query flag, a header, the host name): `MapWhen`. A classic mistake is using `MapWhen` where `UseWhen` was meant: the extra middleware runs, calls `next`, reaches the end of the branch and the client gets a 404 for an URL that works without the condition. The reverse mistake, `UseWhen` for a mini-app, lets requests fall through into the main pipeline after the branch answered nothing. ## Branches versus endpoints - `app.Map(string, Action<IApplicationBuilder>)` is the **middleware branch** from `MapExtensions`. The `app.Map(pattern, RequestDelegate)` and `app.Map(pattern, Delegate)` overloads on a `WebApplication` come from `EndpointRouteBuilderExtensions` and register a **routed endpoint**, which is a different mechanism. - A branch is evaluated where it sits in the pipeline: middleware registered before it runs for branched requests too, middleware registered after it does not (for `Map` and `MapWhen`). - Branches suit isolated mini-apps (a diagnostics page, a legacy protocol). For per-endpoint behaviour, route groups and endpoint metadata are usually the better tool.

  • A Map branch contains only Use middleware that all call next. What does a matching request get?
    A 404. The branch was built by its own `Build()` call, so its `next` chain ends in the builder's final delegate, which sets 404 when nothing answered. It does not fall back to the main pipeline; give the branch a terminal `Run` or an answering component.
  • Does app.Map("/audio", ...) handle a request for /audiobooks?
    No. `MapMiddleware` uses `PathString.StartsWithSegments`, which matches whole segments only, case-insensitively. `/audio` and `/audio/12` enter the branch; `/audiobooks` continues down the main pipeline.
  • On a WebApplication, how is app.Map("/x", branch => ...) different from app.Map("/x", () => "hi")?
    The first binds to `MapExtensions.Map(IApplicationBuilder, string, Action<IApplicationBuilder>)` and creates a middleware branch. The second binds to an `EndpointRouteBuilderExtensions.Map` overload taking a handler `Delegate` and registers a routed endpoint for any HTTP method.

UseWhen is a side gallery that some visitors walk through before the corridor leads them back to the main route; Map and MapWhen are doors into a separate wing with its own exit, so a visitor who goes in never rejoins the main route.

  • UseWhen and MapWhen behave the same; both return to the main pipeline afterwards.
  • A Map branch that writes nothing falls back to the main pipeline automatically.
  • app.Map("/audio") also matches /audiobooks because it is a plain string prefix check.
  • MapWhen strips the matched segment from Request.Path just like Map does.
  • A UseWhen branch cannot short-circuit, because the main pipeline always runs after it.