liveBook · Manning

RouteValuesDictionary

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

RouteValuesDictionary is a .NET dictionary type that stores route-variable names and their values for an HTTP request.

RouteValuesDictionary stores the names and values captured by route parameters in an HTTP request. HttpRequest.RouteValues exposes it to the selected endpoint as an enumerable collection of KeyValuePair<string, object> entries. section 13.1.5

Useful operations include:

  • Read a value with the string indexer, such as context.Request.RouteValues["country"]. section 13.1.5
  • Inspect Keys, Values, and Count, or test for a name with ContainsKey. section 13.1.5
  • Enumerate entries when an endpoint needs to display or process every captured route parameter. section 13.1.5

Three captured segments

A route pattern of {first}/{second}/{third} matches /apples/oranges/cherries. Iterating context.Request.RouteValues produces first: apples, second: oranges, and third: cherries. 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();

Runnable endpoint code shows route-variable enumeration in Program.cs. section 13.1.5

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

How deep it goes
Explains lookup, enumeration, and inspection members, then stops short of the dictionary's internal implementation.
Examples
Demonstrates three-segment URLs, foreach enumeration, country and city lookups, redirects, and population responses.
What you can do after
Apply it via HttpRequest.RouteValues to retrieve, inspect, enumerate, and process route parameters in endpoints.
How it connects
Connects route parameters with URL routing, routing middleware, HttpRequest, endpoints, and route constraints.

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.