Multiple optional parameters web api attribute routing
{flag:int=3?}
is the problem. it is either optional {flag:int?}
with the default value in the action or {flag:int=3}
.
[HttpGet]
Route("GetIssuesByFlag/{flag:int=3}/{categoryId:int?}/{tagIds?}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag , int? categoryId = null, int?[] tagIds = null)
You currently have 3 optional parameters. when you have just the 1 value routing table wont know which optional parameter you are referring to, hence the 404
Harry
Updated on June 18, 2022Comments
-
Harry almost 2 years
I am new to attribute routing, and I am not sure if this is even possible.
I have an attribute route, which works fine like this:
[HttpGet] [Route("GetIssuesByFlag/{flag:int=3}")] public IEnumerable<IssueDto> GetIssuesByFlag(int flag)
Now I want to add some extra optional parameters to narrow down my search, so I want to add 2 extra optional parameters.
What I have tried:
[HttpGet] [Route("GetIssuesByFlag/{flag:int=3?}/{categoryId:int?}/{tagIds?}")] public IEnumerable<IssueDto> GetIssuesByFlag(int flag , int? categoryId = null, int?[] tagIds = null)
This works fine if my call is
/api/controller/1/2
, but fails with 404 when it comes to/api/controller/1
.How can I achieve this?
Edit 1: Nkosi's answer below worked, however an extra modification was needed.
[HttpGet] [Route("GetIssuesByFlag/{flag:int=3}/{tagIds?}/{categoryId:int?}")] public IEnumerable<IssueDto> GetIssuesByFlag(int flag , List<int> tagIds, int? categoryId = null )
The list or array must be second as it is automatically null if no value is provided and cant be marked as optional with = null.
-
Harry about 7 yearsIt works again if i provide all variables but if i provide just the flag it fails with "message": "No HTTP resource was found that matches the request URI 'localhost:44363/api/Issues/GetIssuesByFlag/1'.", "messageDetail": "No action was found on the controller 'Issues' that matches the request."