liveBook · Manning

Route parameter

As explained in Pro ASP.NET Core 7, Tenth Edition

A route segment variable is a named placeholder in a route pattern that captures a value supplied by a URL path segment.

A route parameter, also called a segment variable, is a named placeholder in a URL pattern. Unlike a literal segment such as `capital`, `{country}` can match different path segments. ASP.NET Core routing passes the captured value to the selected endpoint through `HttpRequest.RouteValues`. Names such as `action`, `area`, `controller`, `handler`, and `page` are reserved. section 13.1.5

Read a value in an endpoint

Register `app.MapGet("capital/{country}", Capital.Endpoint);`. A request for `/capital/uk` supplies `uk` under the key `country`; the endpoint can read it with `context.Request.RouteValues["country"] as string`. A matching `population/{city}` route can supply a different value to another endpoint. Restart ASP.NET Core and request a matching URL to observe the response. section 13.1.5

Choose a pattern that captures exactly what the endpoint needs:

  • `{first}/{second}/{third}` captures three path segments. Enumerate `RouteValues` to inspect their names and values; `/apples/oranges/cherries` provides a quick test. section 13.1.5
  • `files/{filename}.{ext}` captures two values from one segment. The literal period separates them, so `/files/myfile.txt` supplies a filename and extension. section 13.2.1
  • Keep complex patterns testable. A pattern beginning `example/red{color}` matches `/example/redgreen`, but the described matching behavior fails for `/example/redredgreen`; such failures can change between ASP.NET Core releases. section 13.2.1

The same pattern feature reaches other ASP.NET Core entry points. A Razor Page can use `@page "{id:long?}"` to make an `id` segment optional and constrain it to a value parseable as `long`; its handler can receive the value through model binding. A Razor Component can use `@page "/person/{id:long}"` and a matching `[Parameter] public long Id { get; set; }` property. Without a type in the component’s `@page` expression, the property must be a string. section 23.3.1 section 35.2.4

Route values can also drive web-service behavior. A minimal API route under `/api/products/{id}` uses the captured ID to look up one product. In a controller route, an optional `{format?}` value works with `[FormatFilter]` to select JSON or XML from the URL instead of the request’s `Accept` header. section 19.3 section 20.4.4

Listing 13.11 Updating routes in the Program.cs file in the Platform folder
using Platform;

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapGet("{first}/{second}/{third}", async context => {
    await context.Response.WriteAsync("Request Was Routed\n");
    foreach (var kvp in context.Request.RouteValues) {
        await context.Response
            .WriteAsync($"{kvp.Key}: {kvp.Value}\n");
    }
});

app.MapGet("capital/{country}", Capital.Endpoint);
app.MapGet("population/{city}", Population.Endpoint);

app.Run();

The complete `Program.cs` listing shows parameterized route registrations beside an endpoint that prints captured route values. section 13.1.5

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through route registration, value access, split-segment matching, and a matching pitfall without detailing the routing algorithm.
Examples
Tests three-segment paths, filename extensions, capital lookups, and product-ID URLs.
What it assumes
Introduces placeholders from literal routes while assuming familiarity with ASP.NET Core endpoints and request handlers.
What you can do after
Apply it via ASP.NET Core routing to capture path values for endpoint logic and page or component parameters.
How it connects
Connects route parameters to endpoint routing, model binding, Razor Pages, and Razor Components.

Also explained in

Compare how 6 books explain route parameter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.