Introduction

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.

Using Optional Parameters

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:

  • 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:

  • 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".
Using Default Parameters

Default values in routes are used to provide a fallback value when a parameter is not supplied. Here's an example:

Some matching URLs are:

  • /todo/status/ results in "Status: all"
  • /todo/status/completed results in "Status: completed"
Summary

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal