Reputation: 3009
According to http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx#optionals-and-defaults
You can have optional parameters by adding a question mark (?) when using attribute routing. However it does not work for me (ASP.NET Web API 5).
[Route("staff/{featureID?}")]
public List<string> GetStaff(int? featureID) {
List<string> staff = null;
return staff;
}
If I use staff/1
etc it works fine, if I use /staff
I get the usual:
"No HTTP resource was found that matches the request URI..."
"No action was found on the controller that matches the request."
Am I missing a reference or something? Or doing it wrong?
Upvotes: 11
Views: 7705
Reputation: 2126
This is because you always have to set a default value for an optional parameter, even if the default is null. That is why this works:
[Route("staff/{featureID=null}")]
Upvotes: 5
Reputation: 326
I also ran into the same issue and solved it a little differently. However, it still didn't work for me as laid out in that blog post. Instead of adding the default parameter value in the route definition I added it to the function definition.
I had to do this to for my example to work properly because I was using a string
instead of an int
and adding the default in the route definition of null
caused my function parameter to have the string value "null"
.
[Route("staff/{featureID?}")]
public List<string> GetStaff(int? featureID = null) {
List<string> staff = null;
return staff;
}
Upvotes: 9
Reputation: 3009
If I do:
[Route("staff/{featureID=null}")]
instead of
[Route("staff/{featureID?}")]
It works.
Technically this doesn't answer my question but it gets me working!
Upvotes: 1