skip to content

When a proxy publishes an ASP.NET Core app under /lifts, how do UsePathBase and X-Forwarded-Prefix keep routing and generated links correct?

level: middleimportance: should knowfreq 35%

answer

  1. Request.PathBase versus Request.Path
  2. proxy keeps or strips the prefix
  3. UsePathBase("/lifts") then UseRouting
  4. unmatched paths pass through
  5. ForwardedHeaders.XForwardedPrefix

basics

~20 s

If the proxy forwards /lifts/..., UsePathBase("/lifts") moves the prefix from Request.Path to Request.PathBase so routes match and links include it. If the proxy strips it, enable XForwardedPrefix so X-Forwarded-Prefix sets PathBase from a trusted proxy.

solid answer

~30 s

ASP.NET Core splits the URL into `Request.PathBase` (where the app is mounted) and `Request.Path` (what routing matches); `LinkGenerator`, `Url.Action` and `Url.Content("~/...")` put `PathBase` back in front of generated URLs. When the proxy forwards the full path, `app.UsePathBase("/lifts")` moves a matching `/lifts` segment into `PathBase`, so `/lifts/passes/day` routes as `/passes/day`. Requests without the prefix pass through unchanged and still route. With `WebApplication`, routing is added before your middleware unless you call `app.UseRouting()` after `UsePathBase`. When the proxy strips `/lifts` and sends `X-Forwarded-Prefix: /lifts`, routing already works; enable `ForwardedHeaders.XForwardedPrefix` (from a trusted proxy) so links regain the prefix.

code

csharp · 11 lines
csharp
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UsePathBase("/lifts");   // /lifts/passes/day -> PathBase /lifts, Path /passes/day
app.UseRouting();             // route on the trimmed Path

app.MapGet("/passes/day", (LinkGenerator links, HttpContext ctx) =>
    links.GetPathByName(ctx, "season"));   // returns /lifts/passes/season
app.MapGet("/passes/season", () => "Season pass").WithName("season");

app.Run();

go deeper

for a junior

Recall that PathBase holds the mount point and Path holds what routing matches, and that UsePathBase splits the two.

for a middle

Explain the two proxy behaviours, keeping versus stripping the prefix, and which of UsePathBase or XForwardedPrefix fits each.

for a senior

Catch the WebApplication routing-order trap, the pass-through of unprefixed URLs and redirects built from literals during a sub-path rollout.

for a principal

Decide whether apps share a host under path prefixes or get their own host names, weighing link correctness, cookies and proxy complexity.

## PathBase and Path Every ASP.NET Core request carries two path properties: - **`Request.PathBase`**: the part of the URL where the app is mounted, for example `/lifts`. - **`Request.Path`**: the rest, which routing, static files and your endpoints match against, for example `/passes/day`. URL-generating APIs prepend `PathBase`: `LinkGenerator`, `Url.Action`, `Url.RouteUrl` and `Url.Content("~/css/site.css")` all produce `/lifts/...`. A hard-coded string such as `"/passes/day"` does not, which is a common source of broken links after moving an app under a prefix. Suppose the lift-pass shop is published as `https://resort.example/lifts/` by a proxy that also serves other apps on the same host. There are two proxy behaviours to handle. ## Case 1: the proxy keeps the prefix The proxy forwards `/lifts/passes/day` unchanged. Without help, routing sees `/lifts/passes/day` and finds nothing. `app.UsePathBase("/lifts")` fixes it: 1. If `Request.Path` starts with the `/lifts` **segment**, the middleware moves that segment to `PathBase` and leaves `/passes/day` in `Path`. 2. After the rest of the pipeline returns, it restores the original values. 3. If the path does **not** start with `/lifts`, it does nothing: `/passes/day` still reaches routing and is served. `UsePathBase` is not an access filter. With `WebApplication`, the framework inserts `UseRouting` at the start of the pipeline unless your code calls it, so routes would be matched before `UsePathBase` ran. The documented pattern is to call `app.UseRouting()` explicitly after `app.UsePathBase(...)`. ## Case 2: the proxy strips the prefix The proxy forwards `/passes/day` and records the removed part in `X-Forwarded-Prefix: /lifts`. Routing already works, but generated links lack `/lifts` and break for the browser. Options: - **Forwarded headers**: add `ForwardedHeaders.XForwardedPrefix` to `ForwardedHeadersOptions.ForwardedHeaders`. The middleware sets `Request.PathBase` from the header (the value must start with `/`) and keeps any earlier path base in `X-Original-Prefix`. Like every forwarded header, it is applied only from a sender in `KnownProxies` or `KnownIPNetworks`. - **A fixed prefix**: if the proxy sends no header, an inline middleware can assign `context.Request.PathBase = new PathString("/lifts")`. ## Choosing | Proxy behaviour | Use | Effect | |---|---|---| | Forwards `/lifts/passes/day` | `app.UsePathBase("/lifts")`, then `app.UseRouting()` | `PathBase = /lifts`, `Path = /passes/day` | | Forwards `/passes/day` + `X-Forwarded-Prefix: /lifts` | `ForwardedHeaders.XForwardedPrefix` with the proxy trusted | `PathBase = /lifts` for link generation | | Forwards `/passes/day`, no header | set `Request.PathBase` in inline middleware | same, with the prefix hard-coded | ## Pitfalls - Expecting `UsePathBase` to reject unprefixed URLs; it passes them through. - Calling `UsePathBase` after `WebApplication` already ran routing, so routes never see the trimmed path. - Building redirect targets from string literals instead of `LinkGenerator` or `Url` helpers, losing `PathBase`. - Enabling `XForwardedPrefix` without declaring a non-loopback proxy: the header is ignored from unknown senders since 8.0.17 / 9.0.6. ## Checking the result - Return `Request.PathBase` and `Request.Path` from a diagnostic endpoint and call it through the proxy; you should see `/lifts` and the trimmed path. - Generate one link with `LinkGenerator` and one with a literal string; only the first should carry `/lifts`. - Call the app directly without the prefix to confirm whether unprefixed URLs are still served, and decide whether the proxy should block them. Blazor apps have their own base-path rules (`<base href>`), covered with Blazor hosting rather than here.

  • After app.UsePathBase("/lifts"), is the app still reachable at /passes/day without the prefix?
    Yes. `UsePathBase` only acts when `Request.Path` starts with the `/lifts` segment; any other path passes through unchanged and can match a route. If unprefixed access must be blocked, that is the proxy's job or an explicit check, not `UsePathBase`.
  • Why does Results.Redirect("/passes/season") break behind the prefix while LinkGenerator works?
    A literal path is sent to the browser as-is, so it resolves to `https://resort.example/passes/season`, outside the app's mount point. `LinkGenerator` and `Url` helpers prepend `Request.PathBase`, producing `/lifts/passes/season`. Generate redirect targets from route names or `~/` paths instead of string literals.

  • UsePathBase returns 404 for any request that lacks the prefix.
  • UsePathBase works wherever you place it, because WebApplication routes last.
  • Request.Path still contains the prefix after UsePathBase runs.
  • X-Forwarded-Prefix is applied by setting ForwardedHeaders.XForwardedHost.
  • Use UseRewriter to strip /lifts so generated links keep the prefix.