0

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?

3
  • 1
    because the route is not matched, you need to use the url https://localhost:44375/heroes/name=Spider - but using the = in the pattern is unusual. Commented Mar 6, 2021 at 16:44
  • Yes, but I need to create a method that knows how to respond to this specific URL: localhost:44375/heroes/?name=Spider Commented Mar 6, 2021 at 16:47
  • 1
    so you already have the firsrt Get method (as you said, it's invoked). The url you want has a part called query string. The Get method then should be like Get(string name). The second Get makes no sense, just remove the [HttpGet("/name={term}")] Commented Mar 6, 2021 at 16:51

2 Answers 2

1

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

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

Comments

1

There are 2 things to distinguish here - URL parameters versus query parameters. If you want to supply variable while doing you GET HTTP call these are the options:

  1. Variable you want to pass can be part of the URL:

    http://localhost:8080/yourResourceName/{varValue}

     [HttpGet]
     public Task<IActionResult> Get(string varValue)
     {
    
     }
    
  2. Variable you want to pass can be a query parameter:

    http://localhost:8080/yourResourceName?varname={varValue}

     [HttpGet]
     public Task<IActionResult> Get([FromQuery]string varValue)
     {
    
     }
    

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.