How to pass multiple parameters to a get method in ASP.NET Core

前端 未结 12 1458
说谎
说谎 2020-12-04 07:46

How can I pass in multiple parameters to Get methods in an MVC 6 controller. For example I want to be able to have something like the following.

[Route(\"api         


        
12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 07:52

    Why not using just one controller action?

    public string Get(int? id, string firstName, string lastName, string address)
    {
       if (id.HasValue)
          GetById(id);
       else if (string.IsNullOrEmpty(address))
          GetByName(firstName, lastName);
       else
          GetByNameAddress(firstName, lastName, address);
    }
    

    Another option is to use attribute routing, but then you'd need to have a different URL format:

    //api/person/byId?id=1
    [HttpGet("byId")] 
    public string Get(int id)
    {
    }
    
    //api/person/byName?firstName=a&lastName=b
    [HttpGet("byName")]
    public string Get(string firstName, string lastName, string address)
    {
    }
    

提交回复
热议问题