ASP.NET Core › Endpoint Metadata, Route Constraints & Templates
How do you define optional route parameters, and what's the difference between an optional parameter and one with a default value?
IntermediateAnswer
Appending a question mark to a route parameter ({id?}) makes it optional, resulting in a null/default value in the handler if the URL segment is omitted entirely. A default value (using = syntax in older routing conventions, or a C# default parameter value in minimal APIs) instead provides a specific fallback value rather than null when the segment is absent -- both let one route template match URLs with or without that particular segment present.
// Optional: results in null if omitted
app.MapGet("/products/{category?}", (string? category) =>
category is null ? GetAllProducts() : GetByCategory(category));
// Default value: results in "all" if omitted, via C# default parameter
app.MapGet("/products/{category}", (string category = "all") => GetByCategory(category));Real-world example A product listing endpoint supports both /products (showing everything) and /products/electronics (filtered) using a single optional route parameter, avoiding the need for two separately registered route templates.