RBasniak RBasniak - 3 months ago 26
ASP.NET (C#) Question

Search items on database through Web Api and ASP.NET Core

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());
}
}


When I type the url
/api/heroes
the method Get is called. But when I type
/api/heroes/?searchTerm=xxxxx
then the same Get method is called, like if there wasn't any parameter in the URL.

What am I missing?

Answer

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.