我有这个:
[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) { ... }
或者为了获得更大的灵活性,尝试路线限制
参考文献ASP.NET Web API 2 中的属性路由:路由约束
路线限制
路由约束可让您限制路由中的参数
模板已匹配。一般语法是“{参数:约束}”。
例如:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }
[Route("users/{name}"]
public User GetUserByName(string name) { ... }
在这里,只有在“id”段的情况下才会选择第一条路线
URI 是一个整数。否则,将选择第二条路线。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)