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

mstrand picture mstrand · Mar 29, 2016 · Viewed 285k times · Source

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)
    {

    }
}

So I can query like.

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

Answer

antlas picture antlas · Dec 5, 2016

You also can use this:

// 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}";
}

Note: Please refer to metalheart's and metalheart and Mark Hughes for a possibly better approach.