多个可选参数Web API属性路由 [英] Multiple optional parameters web api attribute routing
问题描述
我是属性路由的新手,不确定这是否可行.
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)
但是现在我想添加一些额外的可选参数来缩小搜索范围,所以我想添加2个额外的可选参数.
now however i want to add some extra optional parameters to narrow down my search so i want to add 2 extra optional parameters.
我尝试过的事情:
[HttpGet]
[Route("GetIssuesByFlag/{flag:int=3?}/{categoryId:int?}/{tagIds?}")]
public IEnumerable<IssueDto> GetIssuesByFlag(int flag , int? categoryId = null, int?[] tagIds = null)
如果我的电话是/api/controller/1/2
,这可以正常工作
但在/api/controller/1
This works fine if my call is /api/controller/1/2
but fails with 404 when it comes to /api/controller/1
我该如何实现?
Nkosi的答案在下面很奏效,但是还需要进行额外的修改.
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 )
列表或数组必须是第二个,因为如果没有提供值,则列表或数组将自动为null,并且不能使用= 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
推荐答案
{flag:int=3?}
是问题.它是操作中具有默认值的可选{flag:int?}
或{flag:int=3}
.
{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)
您当前有3个可选参数.当您只有1值路由表时,将不知道您要指的是哪个可选参数,因此404
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
这篇关于多个可选参数Web API属性路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!