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
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)
{
}
To call get with multiple parameter in web api core
[ApiController]
[Route("[controller]")]
public class testController : Controller
{
[HttpGet]
[Route("testaction/{id:int}/{startdate}/{enddate}")]
public IEnumerable<classname> test_action(int id, string startdate, string enddate)
{
return List_classobject;
}
}
In web browser
https://localhost:44338/test/testaction/3/2010-09-30/2012-05-01
Methods should be like this:
[Route("api/[controller]")]
public class PersonsController : Controller
{
[HttpGet("{id}")]
public Person Get(int id)
[HttpGet]
public Person[] Get([FromQuery] string firstName, [FromQuery] string lastName, [FromQuery] string address)
}
Take note that second method returns an array of objects and controller name is in plurar (Persons not Person).
So if you want to get resource by id it will be:
api/persons/1
if you want to take objects by some search criteria like first name and etc, you can do search like this:
api/persons?firstName=Name&...
And moving forward if you want to take that person orders (for example), it should be like this:
api/persons/1/orders?skip=0&take=20
And method in the same controller:
[HttpGet("{personId}/orders")]
public Orders[] Get(int personId, int skip, int take, etc..)
You can simply do the following:
[HttpGet]
public async Task<IActionResult> GetAsync()
{
string queryString = Request.QueryString.ToString().ToLower();
return Ok(await DoMagic.GetAuthorizationTokenAsync(new Uri($"https://someurl.com/token-endpoint{queryString}")));
}
If you need to access each element separately, simply refer to Request.Query
.
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.
Simplest way,
Controller:
[HttpGet("empId={empId}&startDate={startDate}&endDate={endDate}")]
public IEnumerable<Validate> Get(int empId, string startDate, string endDate){}
Postman Request:
{router}/empId=1&startDate=2020-20-20&endDate=2020-20-20
Learning point: Request exact pattern will be accepted by the Controller.