Route attribute routing with query strings when there are multiple routes

北城余情 提交于 2020-02-13 22:24:12

问题


I have this:

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

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

They are called by providing the query string eg Cats?catId=5

However MVC Web API will say you can't have multiple routes that are the same (both routes are "Cats".

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.


回答1:


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

Referencing 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.




回答2:


Try applying constraints on attribute routing.

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

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


来源:https://stackoverflow.com/questions/40526912/route-attribute-routing-with-query-strings-when-there-are-multiple-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!