Welcome to the lesson on optional and default values in ASP.NET Core routing! In the previous lesson, we explored the fundamentals of routing, including how it functions under the hood with EndpointRoutingMiddleware, and the usage of literal segments and parameters. In this lesson, we'll dive deeper and learn how to use optional route parameters and how to provide default values for optional parameters to create more flexible routing configurations.
Optional parameters in routes allow parts of the URL to be omitted, offering a more flexible and user-friendly URL structure. Let's consider an example using optional values:
C#1app.MapGet("/todo/status/{status?}", (string? status) => 2{ 3 var message = status == null ? "Status not specified" : $"Status: {status}"; 4 return Results.Ok(message); 5});
- Navigating to
/todo/status/
results in "Status not specified". - Navigating to
/todo/status/completed
results in "Status: completed".
Here's another example demonstrating optional parameters:
C#1app.MapGet("/todo/{id}/{humanReadableTitle?}", (int id, string? humanReadableTitle) => 2{ 3 var message = string.IsNullOrEmpty(humanReadableTitle) 4 ? $"Todo item: {id}, Title not specified" 5 : $"Todo item: {id}, Title: {humanReadableTitle}"; 6 7 return Results.Ok(message); 8});
- Navigating to
/todo/1
results in "Todo item: 1, Title not specified". - Navigating to
/todo/1/learn-asp-net-core
results in "Todo item: 1, Title: learn-asp-net-core".
Default values in routes are used to provide a fallback value when a parameter is not supplied. Here's an example:
C#1app.MapGet("/todo/status/{status=all}", (string status) => 2{ 3 var message = $"Status: {status}"; 4 return Results.Ok(message); 5});
Some matching URLs are:
/todo/status/
results in "Status: all"/todo/status/completed
results in "Status: completed"
In this lesson, we expanded our routing capabilities in ASP.NET Core by learning how to use optional and default values in routes. These techniques allow for more flexibility and predictability in your web applications. Up next, you'll get hands-on practice to solidify your understanding. Happy coding!