当有多条路由时,带有查询字符串的路由属性路由 [英] Route attribute routing with query strings when there are multiple routes
问题描述
我有这个:
[HttpGet]
[Route("Cats")]
public IHttpActionResult GetByCatId(int catId)
[HttpGet]
[Route("Cats")]
public IHttpActionResult GetByName(string name)
通过提供查询字符串来调用它们,例如 Cats?catId=5
They are called by providing the query string eg Cats?catId=5
然而,MVC Web API 会说你不能有多个相同的路由(两条路由都是Cats".
However MVC Web API will say you can't have multiple routes that are the same (both routes are "Cats".
我怎样才能让它工作,以便 MVC Web API 将它们识别为单独的路由?有什么我可以放入 Route 属性的东西吗?它说 ?
是一个可以放入路由的无效字符.
How can I get this to work so MVC Web API will recognize them as separate routes? Is there something I can put into the Route property? It says that ?
is an invalid character to put into a route.
推荐答案
您可以将有问题的两个操作合二为一
You can merge the two actions in question into one
[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) { ... }
或者为了更灵活地尝试路由约束
Or for more flexibility try route constraints
引用 ASP.NET Web API 2 中的属性路由:路由约束
路线限制
路由约束让你限制路由中的参数模板匹配.一般语法是{parameter:constraint}".例如:
Route constraints let you restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}". For example:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }
[Route("users/{name}"]
public User GetUserByName(string name) { ... }
这里,只有在id"段的情况下,才会选择第一条路线URI 是一个整数.否则,将选择第二条路线.
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.
这篇关于当有多条路由时,带有查询字符串的路由属性路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!