I would like to pass a query parameter to a Controller in ASP.NET Core. Here are the two related methods:
[Produces("application/json")]
[Route("api/Heroes")]
public class HeroesController : Controller
{
[HttpGet]
[NoCache]
public JsonResult Get()
{
return new JsonResult(_context.Heroes.ToArray());
}
[HttpGet("{searchTerm}", Name = "Search")]
//GET: api/Heroes/?searchterm=
public JsonResult Find(string searchTerm)
{
return new JsonResult(_context.Heroes.Where(h => hero.Name.Contains(searchTerm)).ToArray());
}
}
/api/heroes
/api/heroes/?searchTerm=xxxxx
Based on your code you can try to do this:
[Produces("application/json")]
[Route("api/Heroes")]
public class HeroesController : Controller
{
[HttpGet]
[NoCache]
//GET: api/Heroes
//GET: api/Heroes?searchTerm=
public JsonResult Get(string searchTerm) //string is nullable, so it's good for optional parameters
{
if (searchTerm == null)
{
...
}
else
{
...
}
}
}
You haven't to put query string parameters in the decorator because they are automatically mapped from methods parameters.