Multiple optional parameters web api attribute routing

☆樱花仙子☆ 提交于 2019-12-23 15:24:08

问题


Hi guys i am new to attribute routing and not sure if this is even possible.

What i have is an attribute route which works fine like this

[HttpGet]
[Route("GetIssuesByFlag/{flag:int=3}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag)

now however 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 bellow 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


回答1:


{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




回答2:


Use a query string.

[HttpGet]
    [Route("GetIssuesByFlag/{flag:int=3?}")]
    public IEnumerable<IssueDto> GetIssuesByFlag(int flag, List<int> tagIds, int? categoryId = null)

Url: /getissuesbyflag/1?tagIds=2,5,6&categoryId=56

You really should use query strings for optional parameters and path parameters if they are required.



来源:https://stackoverflow.com/questions/42114879/multiple-optional-parameters-web-api-attribute-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!