In ASP.NET Core 10, how does app.MapFallback decide which requests it handles, and why can it hide 404 and 405 responses from API clients?
answer
- {*path:nonfile} by default
- Order = int.MaxValue
- no HTTP method metadata
- Fallback in the display name
- narrow the pattern or the methods
basics
~20 sMapFallback maps a catch-all {*path:nonfile} endpoint with Order int.MaxValue, so it runs only when nothing better matches. It accepts every method, so unknown /api URLs get its response instead of 404, and wrong methods reach it instead of a 405.
solid answer
~40 s`app.MapFallback(handler)` registers an endpoint with the pattern `{*path:nonfile}` and `Order = int.MaxValue`, the lowest priority. Every other matching endpoint beats it, so it only runs for paths nothing else claims and whose last segment does not look like a file name, which keeps `/app.js` a real 404. Its display name starts with `Fallback`. Two side effects surprise API teams. First, `GET /api/ordres/42`, a typo, now returns whatever the fallback returns, often a 200 with a SPA shell, instead of 404. Second, the fallback has no method metadata, so it accepts every verb, and routing only answers 405 when nothing at the path accepts all methods; `DELETE /api/orders/42` on a GET-only route now hits the fallback. Fixes: give the fallback a narrower pattern with `MapFallback("/app/{*path:nonfile}", ...)`, or restrict its methods.
code
csharp · 12 linesvar app = WebApplication.CreateBuilder(args).Build();
app.MapGet("/api/orders/{id:int}", (int id) => Results.Ok(new { id }));
// SPA shell only for GET, so DELETE /api/orders/42 still answers 405
app.MapFallback(() => Results.Content("<!doctype html><div id=app></div>", "text/html"))
.WithMetadata(new HttpMethodMetadata(new[] { HttpMethods.Get }));
// Unknown API paths answer 404 instead of the SPA shell
app.MapGet("/api/{**rest}", () => Results.NotFound());
app.Run();go deeper
Recall that MapFallback handles requests no other endpoint matched, typically to serve a single-page app's shell.
Explain the {*path:nonfile} pattern and Order int.MaxValue, and why unknown API paths then return the fallback's 200.
Spot that a method-less fallback suppresses 405s under it and fix it with a narrower pattern, HttpMethodMetadata, or an API-specific 404 route, backed by a test.
Decide whether one host should serve both a SPA and an API, and if so define path ownership so fallbacks can never mask API errors.
## What MapFallback registers `MapFallback` is the endpoint-routing way to say "if nothing else matched, run this". In the v10.0.12 source: - `app.MapFallback(handler)` uses the default pattern `FallbackEndpointRouteBuilderExtensions.DefaultPattern`, which is `{*path:nonfile}`. - `app.MapFallback(pattern, handler)` lets you choose the pattern. - Both set the endpoint's `Order` to **`int.MaxValue`**, so every other matching endpoint has higher priority. - Minimal API fallbacks get a display name prefixed with `Fallback`, which is what appears in logs. The pattern does the filtering. `{*path}` is a catch-all that matches every path, including `/`. The `nonfile` constraint rejects a value whose last segment contains a dot followed by non-dot characters, so `/orders/42` and `/` reach the fallback while `/app.js` and `/logo.png` do not and stay 404 when no static file exists. ## The intended use A single-page app served by the same host needs every client-side route, such as `/track/42`, to return the app's shell so the browser router can take over. A fallback does exactly that without a route per page. (`MapFallbackToFile("index.html")` is the static-file variant of the same mechanism.) ## How it hides API errors Put the SPA fallback next to a food-delivery API: ```csharp app.MapGet("/api/orders/{id:int}", (int id) => Results.Ok(new { id })); app.MapFallback(() => Results.Content(SpaShell.Html, "text/html")); ``` | Request | Without the fallback | With the fallback | |---|---|---| | `GET /api/orders/42` | 200 from the API | 200 from the API | | `GET /api/ordres/42` (typo) | 404 | **200 with the SPA shell** | | `DELETE /api/orders/42` | 405, `Allow: GET` | **200 with the SPA shell** | | `GET /app.js` (missing) | 404 | 404 (`nonfile` rejects it) | The second row is plain priority: the typo path matches nothing but the catch-all. The third row is subtler. Routing's HTTP-method policy adds its 405 rejection endpoint only when **no endpoint at that path accepts every method**. The fallback has no `HttpMethodMetadata`, so it accepts every method and sits under every API path; the policy therefore sends the DELETE to the fallback instead of producing a 405. A client library that expects JSON then fails to parse an HTML page with status 200, which is much harder to debug than a 404 or 405. ## Fixing it Pick whichever fits the app: 1. **Narrow the pattern.** If the SPA lives under a prefix, use `app.MapFallback("/app/{*path:nonfile}", ...)`; API paths are then outside the catch-all entirely. 2. **Restrict the methods.** Chaining `.WithMetadata(new HttpMethodMetadata(new[] { "GET" }))` makes the fallback GET-only, so wrong-method requests to API paths get their 405 back; unknown GET paths still reach it. 3. **Give the API its own not-found handler.** A GET catch-all such as `app.MapGet("/api/{**rest}", () => Results.NotFound())` keeps typos out of the SPA, because its default order 0 beats the fallback. Mapping it with `app.Map` instead would accept every method and, like the fallback, turn wrong-method requests under `/api` into 404s rather than 405s. 4. **Test it.** An integration test that sends an unknown `/api` URL and a wrong method, and asserts 404 and 405, catches the regression the day someone adds a fallback. ## Fallbacks for MVC and Razor Pages The same mechanism exists for the other programming models: `app.MapFallbackToController("Index", "Home")` sends unmatched paths to a controller action, and `app.MapFallbackToPage("/Index")` to a Razor Page. Both also take a pattern overload, so the advice is the same: decide which part of the URL space the fallback owns, and keep API paths out of it. ## Fallbacks and ordering Because `Order` is compared before route precedence, the fallback loses even to endpoints with very general templates such as `/{slug}`. Conversely, if you give another endpoint `WithOrder(int.MaxValue)` and a template that ties with the fallback, you can create an ambiguity, so leave `int.MaxValue` to fallbacks. ## What interviewers listen for - The default pattern `{*path:nonfile}` and `Order = int.MaxValue`. - That files with extensions are excluded on purpose. - That a fallback accepts every method and therefore suppresses 405s beneath it. - A concrete fix: a narrower pattern, method metadata, or an API-specific 404.
- Why does the default fallback pattern use the nonfile constraint?So requests for things that look like files, such as `/app.js` or `/logo.png`, are not answered with the fallback's response. If a static asset is missing, the browser should get a 404, not an HTML shell served as JavaScript. `nonfile` rejects a value whose last segment has a dot followed by non-dot characters.
- In the snippet with a GET-only fallback and a GET /api/{**rest} 404 route, which endpoint handles GET /api/ordres/42?The `/api/{**rest}` endpoint. Both it and the fallback match, but the fallback has `Order = int.MaxValue` while the API route has the default order 0, and `Order` is compared before precedence. The client therefore gets a 404 instead of the SPA shell.
- Says MapFallback runs before other endpoints because it is a catch-all.
- Expects a missing /app.js to receive the fallback's HTML response.
- Believes adding a fallback never changes the status codes of API routes.
- Assumes the fallback only accepts GET requests by default.
- Gives ordinary endpoints Order int.MaxValue to make them run last like a fallback.