11

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?

Adam Marshall
  • 3,010
  • 9
  • 42
  • 80

3 Answers3

9

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;
}
Luke Pfeiffer
  • 316
  • 2
  • 3
  • Looking at that, it makes perfect sense as an optional argument on a normal method would be done that way, good insight on the "null" part as well – Adam Marshall Oct 27 '15 at 18:39
5

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}")]
Oleks
  • 31,955
  • 11
  • 77
  • 132
Robert Corvus
  • 2,054
  • 23
  • 30
  • 7
    Then why have the '?' character functionality at all? – Sal Feb 07 '17 at 16:04
  • `[HttpGet][Route("GetFilterData/{job=null}")]public async Task> GetFilterData(string job = null)` worked for me, it seems Microsoft broke the old pattern... – fartwhif May 11 '22 at 17:44
1

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!

Adam Marshall
  • 3,010
  • 9
  • 42
  • 80