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
