1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.