Route attribute routing with query strings when there are multiple routes

后端 未结 2 576
野的像风
野的像风 2021-01-06 14:01

I have this:

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

[HttpGet]
[Route(\"Cats\")]
public IHttpActionResult GetByName(strin         


        
相关标签:
2条回答
  • 2021-01-06 14:21

    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.

    0 讨论(0)
  • 2021-01-06 14:27

    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)
    
    0 讨论(0)
提交回复
热议问题