How to trigger ASP.NET Core API function when the parameter is included in URL

I try to trigger a specific method (the second one) in HeroesController class:

    [HttpGet]
    public IEnumerable<Hero> Get()
    {
        return Heroes;
    }

    [HttpGet("/name={term}")]
    public IEnumerable<Hero> Get(string term)
    {
        return Heroes;
    }

After calling this URL:

https://localhost:44375/heroes/?name=Spider 

The first method is triggered, not the second. Why is that so? How to trigger the second one which receives term parameter?

Answer

As pointed out in the comments by King King, the url is not matched, but the best way to do this is;

[HttpGet] 
public IEnumerable<Hero> Get([FromQuery] string term) 
{ 
    return Heroes; 
}

Then the endpoint would be hit if a query parameter, term is passed https://localhost:44375/heroes?term=Spider

Leave a Reply

Your email address will not be published. Required fields are marked *