In this article, we are going to look at how to use optional parameters in ASP.NET Core Web API routing. Additionally, we are going to learn how to use optional parameters with route constraints.

To download the source code for this article, you can visit our GitHub repository.

Let’s start.

What Are Optional Parameters in ASP.NET Core

In a route template, an optional parameter is a URI or endpoint parameter that we can remove since default values have been supplied to replace it. Using optional parameters can help increase flexibility in our code.

Support Code Maze on Patreon to get rid of ads and get the best discounts on our products!
Become a patron at Patreon!

So, how do we make a parameter optional?

We can make a route parameter optional by adding “?” to it. The only gimmick is while declaring a route parameter as optional, we must specify a consequent default value for it:

public WeatherForecast GetById(int id = 1)
    var forecasts = Get();

    var weatherForecast = forecasts.Where(w => w.Id ==  id).FirstOrDefault()!;

    return weatherForecast;

In this case, we assign 1 as a default value for the id parameter in the GetById action method. When we call either  /api/WeatherForecast/GetById or /api/WeatherForecast/GetById/1 , we would get the same result.

Also, as we can see, we are using attribute routing to provide an optional parameter. If you are not familiar with attribute routing in ASP.NET Core, you can check out our Routing in ASP NET Core article for more information.

Optional Parameters in ASP.NET Core With Route Constraints

We use route constraints when we need to define how the parameters in the route template are matched:

public Product GetBy(string name)
    var products = Get();

    return products.Where(p => p.Name == name).FirstOrDefault()!;    

public Product GetBy(int id)
    var products = Get();

    return products.Where(p => p.Id == id).FirstOrDefault()!;

Here, we have two different GetBy actions, where the second action has a route with the int route constraint applied. This means we can only access GetBy(int id) action when we pass an integer as a parameter to it.

Now, if we want to use optional parameters with route constraints, we can simply specify a default parameter in the action method:

public Product GetById(int id = 1)
    var products = Get();

    return products.Where(p => p.Id == id).FirstOrDefault()!;

Now, we apply the int constraint to our action but also, we make it optional and we don’t have to pass it in our request. By default, the value of the id parameter will be 1.


In this article, we learned about optional parameters and how we can use them in ASP.Net core Web API attribute routing.

Liked it? Take a second to support Code Maze on Patreon and get the ad free reading experience!
Become a patron at Patreon!