liveBook · Manning

URL pattern

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

A route pattern is a template that defines the URL structure and segment variables a route can match.

A URL pattern connects a request path to an endpoint. ASP.NET Core routing compares the path—not the hostname or query string—with patterns registered for routes. A matching route sends the request to its endpoint; a pattern is conventionally written without a leading slash. section 13.1.2

Start with fixed segments. The pattern `capital/uk` matches `/capital/uk`, but not `/capital`, `/capital/europe/uk`, or `/name/uk`: the segments must match in number and content. In `Program.cs`, `app.MapGet("capital/uk", Capital.Endpoint)` also limits the route to GET requests. Use `MapPost`, `MapPut`, `MapDelete`, `MapMethods`, or `Map` when the HTTP-method requirement differs. section 13.1.4 section 13.1.2

Replace a fixed segment with a variable when the endpoint needs its value. `app.MapGet("capital/{country}", Capital.Endpoint)` matches paths such as `/capital/uk` and `/capital/france`; the endpoint can read `context.Request.RouteValues["country"]`. This avoids selecting an endpoint with routing and then parsing the path again inside it. Variable names cannot be `action`, `area`, `controller`, `handler`, or `page`. section 13.1.5

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 `Program.cs` routes show named path segments feeding the capital and population endpoints; the three-segment route also prints the values routing extracted. section 13.1.5

Adjust the pattern when a simple one-variable-per-segment route is too narrow:

  • `files/{filename}.{ext}` captures two values from one segment. The literal period separates them so routing can tell where one value ends. section 13.2.1
  • `capital/{country=France}` supplies `France` when the second segment is absent: both `/capital` and `/capital/uk` match. section 13.2.2
  • Optional segments and constraints can change which URLs match. For example, `{id:long?}` makes an `id` segment optional while requiring a supplied value to parse as a long. section 13.4 section 23.3.1

Patterns also work in Razor Pages. `@page "{id:long?}"` adds a segment variable to a page route; `@page "/lists/suppliers"` overrides the file-based route. To add a route without replacing an existing page route, configure `RazorPagesOptions` and call `Conventions.AddPageRoute("/Index", "/extra/page/{id:long?}")`. section 23.3.1 section 23.3.2

Test patterns with actual URLs, especially complex segments: some matching failures have changed between ASP.NET Core releases. Routes can also generate response URLs that target an endpoint, so matching is not their only use. section 13.2.1 section 13.4

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

How deep it goes
Works through literal matching, variables, defaults, multi-value segments, and Razor Page configuration, with a warning about complex matching failures.
Examples
Uses capital and population endpoints, filename extensions, and Razor Page URLs to show which paths match.
What it assumes
Assumes basic ASP.NET Core application code while explaining request-path segments and route variables before using them.
What you can do after
Apply it via ASP.NET Core route mappings or Razor Page configuration to select endpoints and read values from request paths.
How it connects
Connects endpoint routing, route values, HTTP methods, Razor Pages, route constraints, and URL generation.

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.