In this article, I am going to discuss Optional Parameters in Web API Attribute Routing with some examples. Please read our previous article before proceeding to this article as we are going to work with the same example that we started in the Web API Attribute Routing article where we discussed the following things.
- Why we need attribute routing?
- What is Attribute Routing?
- How to Implement Attribute Routing?
- What are the advantages of using Attribute Routing?
Optional Parameters in Web API Attribute Routing and Default Values:
You can make a URI parameter as optional by adding a question mark (“?â€) to the route parameter. If you make a route parameter as optional then you must specify a default value by using parameter = value for the method parameter.
We are going to work with the same example that we created in our last Video. In our last Video, we use the following Student Model
Along with we modify the WebApiConfig class as shown below.
Lets modify the Student Controller as shown below.
In the above example, /api/students and /api/students/1 return the same resource. Alternatively, you can also specify a default value inside the route template as shown in the below image.
This is almost the same as the previous example, but there is a slight difference in the behavior when the default value is applied.
In the first example (“{stdid?}â€), here the default value 1 is directly assigned to the action method parameter, so the method parameter will have this value exactly.
In the second example (“{stdid=1}â€), the default value “1†assigned to the method parameter through the model-binding process. The default model-binder in Web API will convert the value “1†to the numeric value 1.
In most of the cases, unless you have custom model binders in your pipeline, the two forms will be equivalent.