Search code examples
c#asp.net-web-apiasp.net-web-api-routing

Route attribute routing with query strings when there are multiple routes


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.


Solution

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