skip to content

In ASP.NET Core, when app.Map("/guide", ...) handles a request for /guide/tours/7, what do Request.PathBase and Request.Path hold inside the branch?

level: seniorimportance: nice to knowfreq 22%

answer

  1. the matched segment moves
  2. PathBase gains /guide
  3. Path becomes /tours/7
  4. restored in a finally block
  5. preserveMatchedPathSegment: true opts out

basics

~20 s

Inside the branch PathBase is the old PathBase plus /guide and Path is /tours/7. Map restores both when the branch returns. Branch code therefore sees paths relative to /guide, while URLs rebuilt from PathBase plus Path still include it.

solid answer

~40 s

`MapMiddleware` matches with `StartsWithSegments(pathMatch, out matched, out remaining)` and, by default, sets `Request.PathBase = PathBase.Add(matched)` and `Request.Path = remaining` before calling the branch, restoring both in a `finally`. For `/guide/tours/7` with an empty base, the branch sees `PathBase` `/guide` and `Path` `/tours/7`. That is what lets you mount a self-contained mini-app: its middleware matches on `Path` as if it lived at the root (static files under the branch, for example, are looked up by `Path`), while anything that builds absolute URLs from `PathBase` + `Path`, such as `GetDisplayUrl`, still produces `/guide/tours/7`. Code inside the branch that checks `Path.StartsWithSegments("/guide")` no longer matches. The overload `Map(pathMatch, preserveMatchedPathSegment: true, ...)` leaves both properties untouched.

code

csharp · 15 lines
csharp
app.Map("/guide", guide =>
{
    guide.UseStaticFiles();                    // /guide/audio/7.mp3 -> wwwroot/audio/7.mp3
    guide.Run(async ctx =>
    {
        // For GET /guide/tours/7:
        //   ctx.Request.PathBase == "/guide"
        //   ctx.Request.Path     == "/tours/7"
        await ctx.Response.WriteAsync($"{ctx.Request.PathBase} | {ctx.Request.Path}");
    });
});

// Keep the full path visible inside the branch instead
app.Map("/raw", preserveMatchedPathSegment: true, raw =>
    raw.Run(ctx => ctx.Response.WriteAsync(ctx.Request.Path.Value!))); // "/raw/..."

go deeper

for a junior

Remember that Map strips the matched prefix from Path for the code inside the branch.

for a middle

Explain where the prefix goes, how PathBase.Add stacks under an existing base, and the preserveMatchedPathSegment overload.

for a senior

Predict how static files, path checks, logs and generated URLs behave inside a mounted branch, and debug a branch whose path checks never match.

for a principal

Weigh mounting mini-apps under path prefixes in one host against separate hosts behind a proxy, considering URL generation and operational isolation.

## PathBase and Path ASP.NET Core splits the request URL's path into two `PathString` properties on `HttpRequest`: - **`PathBase`**: the part of the path that identifies *where the app (or branch) is mounted*. It is empty for an app at the site root. - **`Path`**: the remainder, the part the app itself interprets. Most middleware, including routing and the static file middleware, matches on `Path` only. Code that needs the full URL concatenates `PathBase` and `Path`; `UriHelper.GetDisplayUrl` does exactly that. ## What Map does to them `app.Map("/guide", branch => ...)` inserts `MapMiddleware`. Per request it: 1. Calls `Request.Path.StartsWithSegments("/guide", out var matched, out var remaining)`. The comparison matches whole segments, case-insensitively. 2. On a match, saves the current `PathBase` and `Path`. 3. Sets `PathBase = PathBase.Add(matched)` and `Path = remaining`. 4. Awaits the branch delegate. 5. In a `finally` block, restores the saved values, so middleware outside the branch sees the original request on the way out. For `/guide/tours/7` on an app at the root: | Where | `PathBase` | `Path` | |---|---|---| | before the branch | (empty) | `/guide/tours/7` | | inside the branch | `/guide` | `/tours/7` | | after the branch returns | (empty) | `/guide/tours/7` | If the app was already mounted under a base (say `/museum`), the branch sees `/museum/guide` as `PathBase`: `Add` appends, it does not replace. ## Why it matters The rewrite is what makes `Map` useful for mounting a mini-app that was written as if it lived at the root: - **Static files in a branch**: `guide.UseStaticFiles()` inside `Map("/guide")` looks files up by `Path`, so `/guide/audio/7.mp3` resolves to `audio/7.mp3` under the web root. - **Path checks inside the branch** must use the relative form. `ctx.Request.Path.StartsWithSegments("/guide/admin")` never matches inside the branch; `"/admin"` does. - **Absolute URLs** built from `PathBase` + `Path` (redirect targets, `GetDisplayUrl`, links in a page) still contain `/guide`, so a branch can generate correct links without knowing where it is mounted. - **Logging inside the branch** that records only `Path` loses the `/guide` prefix; log both properties or the display URL. ## A worked mount The museum audio-guide API mounts its handset mini-app under `/guide`. The mini-app was first written as a separate app at the root, with audio files at `/audio/...` and a tour page at `/tours/{n}`. Mounted with `app.Map("/guide", guide => ...)`: 1. `GET /guide/audio/7.mp3` enters the branch with `Path` `/audio/7.mp3`, so the branch's `UseStaticFiles()` finds `wwwroot/audio/7.mp3` without any change to the mini-app. 2. `GET /guide/tours/7` reaches the branch's terminal handler with `Path` `/tours/7`, so its own path parsing keeps working. 3. When the handler builds a link to the next stop as `PathBase + "/tours/8"`, it produces `/guide/tours/8`, which the handset can follow. 4. A request for `/guidebook` does not match, because matching is by whole segment, and continues down the main pipeline. The one thing that breaks is code that hard-coded the prefix: a branch middleware checking `Path.StartsWithSegments("/guide/admin")` silently never matches. ## Opting out `Map` has a third overload: `Map(PathString pathMatch, bool preserveMatchedPathSegment, Action<IApplicationBuilder> configuration)`. With `preserveMatchedPathSegment: true`, `MapMiddleware` still branches on the prefix but calls the branch without touching `PathBase` or `Path`, so the branch sees `/guide/tours/7` as `Path`. Use it when the branch's components expect the full path. ## Edge cases interviewers raise - **Trailing slash**: `app.Map("/guide/", ...)` throws `ArgumentException` ("The path must not end with a '/'") when the pipeline is configured. - **Nesting**: `Map` inside `Map` stacks segments: an inner `Map("/tours")` inside `Map("/guide")` sees `PathBase` `/guide/tours`. - **MapWhen and UseWhen** never rewrite either property; only `Map` (with the default overloads) does. - **Restoration happens on the way out**: an outer middleware that logs after `await next(context)` sees the original `Path` again, which is usually what access logs want.

  • Do middleware registered before app.Map see the rewritten Path after the branch returns?
    No. `MapMiddleware` restores the saved `PathBase` and `Path` in a `finally` block, so outer middleware running code after `await next(context)` see the original values, even if the branch threw.
  • What does app.Map("/guide/", ...) do?
    It throws an `ArgumentException` saying the path must not end with a '/', when that line runs during pipeline configuration. Pass `/guide` instead; segment-aware matching already covers `/guide/` and everything below it.

  • Map leaves Request.Path unchanged and only decides whether the branch runs.
  • Inside the branch, Path still starts with /guide, so checks should include it.
  • Map overwrites PathBase with /guide even when the app already had a base path.
  • MapWhen moves the matched segment into PathBase just like Map does.
  • The rewritten Path stays in place for outer middleware after the branch returns.