多条路由时使用查询字符串路由属性路由

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

但是 MVC Web API 会说你不能有多个相同的路由(两条路由都是 "Cats".

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

尝试对属性路由应用约束。

[HttpGet]
[Route("Cats/{catId:int}")]
public IHttpActionResult GetByCatId(int catId)

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

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

[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:

[Route("users/{id:int}"]
public User GetUserById(int id) { ... }

[Route("users/{name}"]
public User GetUserByName(string name) { ... }

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.