liveBook · Manning

RouteValues property

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

The RouteValues property is an HttpRequest property that exposes the route values extracted from a matched request URL.

HttpRequest.RouteValues exposes the values captured from named segments in a matched URL. It returns a RouteValuesDictionary whose keys are segment-variable names and whose values are the extracted path content. section 13.1.5

Use the returned dictionary to inspect route data:

  • Retrieve a value by name with RouteValues["country"]. section 13.1.5
  • Enumerate key-value pairs to display every matched segment variable. section 13.1.5
  • Use Keys, Values, Count, and ContainsKey to inspect available route data. section 13.1.5

Reading route parameters in an endpoint

For a route such as capital/{country}, read context.Request.RouteValues["country"] and use the resulting value to choose a capital, redirect, or response. section 13.1.5

Listing 13.8 Using segment variables 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/uk", new Capital().Invoke);
app.MapGet("population/paris", new Population().Invoke);

app.Run();

A runnable endpoint enumerates RouteValues for a three-segment pattern and prints each variable name with its extracted URL value. section 13.1.5

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

How deep it goes
Defines RouteValuesDictionary and demonstrates enumeration and keyed access without detailing the full route-scoring algorithm.
Examples
Uses three-segment URLs and country or city parameters for routing, capital responses, population responses, and redirects.
What you can do after
Apply it via HttpRequest to enumerate matched values or retrieve a named route parameter inside an endpoint.
How it connects
Connects route values with segment variables, endpoints, routing middleware, and URL route patterns.

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.