Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute Routing - optional parameter not working?

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?

like image 213
Adam Marshall Avatar asked Oct 27 '15 10:10

Adam Marshall


3 Answers

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;
}
like image 183
Luke Pfeiffer Avatar answered Oct 12 '22 21:10

Luke Pfeiffer


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!

like image 33
Adam Marshall Avatar answered Oct 12 '22 21:10

Adam Marshall


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}")]
like image 5
Robert Corvus Avatar answered Oct 12 '22 22:10

Robert Corvus