ASP.NET5 MVC 6 routing with optional parameter / default parameter value
Optional URI Parameters and Default Values
You can make a URI parameter optional by adding a question mark to the route parameter. If a route parameter is optional, you must define a default value for the method parameter.
[HttpGet("machine/{machineId}/{cnt:int?}")]
public IActionResult GetReportsByMachineId(string machineId, int cnt = 10) {...}
In this example, api/report/machine/nazwa_maszyny/10
and api/report/machine/nazwa_maszyny
return the same resource.
Alternatively, you can specify a default value inside the route template, as follows:
[HttpGet("machine/{machineId}/{cnt:int=10}")]
public IActionResult GetReportsByMachineId(string machineId, int cnt) {...}
This is almost the same as the previous example, but there is a slight difference of behavior when the default value is applied.
In the first example ("{cnt:int?}"), the default value of 10 is assigned directly to the method parameter, so the parameter will have this exact value.
In the second example ("{cnt:int=10}"), the default value of "10" goes through the model-binding process. The default model-binder will convert "10" to the numeric value 10. However, you could plug in a custom model binder, which might do something different.