加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 当有多条路由时,使用查询字符串路由属性路由

发布时间:2020-12-15 23:35:53 所属栏目:百科 来源:网络整理
导读:我有这个: [HttpGet][Route("Cats")]public IHttpActionResult GetByCatId(int catId)[HttpGet][Route("Cats")]public IHttpActionResult GetByName(string name) 它们通过提供查询字符串来调用,例如Cats?catId = 5 但是,MVC Web API会说你不能有多条相同
我有这个:

[HttpGet]
[Route("Cats")]
public IHttpActionResult GetByCatId(int catId)

[HttpGet]
[Route("Cats")]
public IHttpActionResult GetByName(string name)

它们通过提供查询字符串来调用,例如Cats?catId = 5

但是,MVC Web API会说你不能有多条相同的路由(两条路由都是“Cats”).

我怎样才能使其工作,以便MVC Web API将它们识别为单独的路由?有什么东西我可以放入Route属性吗?它说?是放入路线的无效字符.

解决方法

您可以将有问题的两个操作合并为一个

[HttpGet]
[Route("Cats")]
public IHttpActionResult GetCats(int? catId = null,string name = null) {

    if(catId.HasValue) return GetByCatId(catId.Value);

    if(!string.IsNullOrEmpty(name)) return GetByName(name);

    return GetAllCats();
}

private IHttpActionResult GetAllCats() { ... }

private IHttpActionResult GetByCatId(int catId) { ... }    

private IHttpActionResult GetByName(string name) { ... }

或者为了更灵活地尝试路线约束

参考Attribute Routing in ASP.NET Web API 2 : Route Constraints

Route Constraints

Route constraints let you restrict how the parameters in the route
template are matched. The general syntax is “{parameter:constraint}”.
For example:

06001

Here,the first route will only be selected if the “id” segment of the URI is an integer. Otherwise,the second route will be chosen.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读