如何将多个参数传递给 ASP.NET Core 中的 get 方法

如何将多个参数传递给 ASP.NET Core 中的 get 方法

问题描述:

如何将多个参数传递给 MVC 6 控制器中的 Get 方法.例如,我希望能够拥有以下内容.

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/[controller]")]
public class PersonController : Controller
{
    public string Get(int id)
    {
    }

    public string Get(string firstName, string lastName)
    {

    }

    public string Get(string firstName, string lastName, string address)
    {

    }
}

这样我就可以查询了.

api/person?id=1
api/person?firstName=john&lastName=doe
api/person?firstName=john&lastName=doe&address=streetA

你也可以使用这个:

// GET api/user/firstname/lastname/address
[HttpGet("{firstName}/{lastName}/{address}")]
public string GetQuery(string id, string firstName, string lastName, string address)
{
    return $"{firstName}:{lastName}:{address}";
}

注意:请参考metalheart的回答和 Mark Hughes 以获得可能更好的方法.

Note: Please refer to the answers from metalheart and Mark Hughes for a possibly better approach.