这应该是一个快速的。我有两条路线:
[HttpGet]
[Route("{id}")]
[ResponseType(typeof(Catalogue))]
public IHttpActionResult Get(string id) => Ok(_catalogueService.Get(id));
和
[HttpGet]
[Route("{numberOfResults:int}")]
[ResponseType(typeof(IEnumerable<Catalogue>))]
public IHttpActionResult List(bool active, int numberOfResults) => Ok(_catalogueService.List(active, numberOfResults));
当我使用邮递员尝试列出我的目录时,我传递了这样的东西
/目录/10
我希望它在我的控制器中采用List
方法。同样,如果我想获取目录,我会传递如下内容:
/目录/AB100
我的路由正常工作,但我最近对List
方法进行了更改(我添加了活动布尔值(,现在我的路由无法正常工作。我上面给出的两个例子都被错误的Get
方法捕获。
有没有办法解决这个问题?
为 active
添加一个默认值,并将其作为可选参数放在numberOfResults
参数之后。
[HttpGet]
[Route("{numberOfResults:int}")]
[ResponseType(typeof(IEnumerable<Catalogue>))]
public IHttpActionResult List(int numberOfResults, bool active = true) => //assuming active default
Ok(_catalogueService.List(active, numberOfResults));
由于额外的必需 active
参数,默认情况下它将不再与原始重载路由匹配,因为它希望active
成为 URL 的一部分,即使不在路由模板中也是如此。
喜欢
/catalogues/10?active=true
通过使该参数可选,这意味着它现在可以像以前一样将预期行为与从 URL 中省略时提供给操作的active
值进行匹配