5

I trying to achieve something like this

namespace CoreAPI.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values

        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        [HttpGet]
        public string GetValue(string name,string surname)
        {
            return "Hello " + name;
        }
    }
}

I want to call this controller method by using both of these URLs:

  1. http://localhost:11979/api/values/Getvalues/John/lawrance
  2. http://localhost:11979/api/values/GetValues?name=john&surname=lawrance
0

1 Answer 1

9

You can solve this by defining multiple routes on top of the controller method

[HttpGet("GetValues")]
[HttpGet("GetValues/{name}/{surname}")]
public string GetValue(string name, string surname)
{
    return "Hi" + name;
}

This will work with http://localhost:11979/api/values/GetValues/John/lawrance and http://localhost:11979/api/values/GetValues?name=john&surname=lawrance

To add more:

[HttpGet]
[Route("GetValues")]
[Route("GetValues/{name}/{surname}")]
public string GetValue(string name,string surname)
{
    return "Hello " + name + " " + surname;
}

This also works.

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

4 Comments

"You can do one or the other in asp.net core" - So we can't do two types of routing on the single method.
[HttpGet] [Route("GetValue")] [Route("GetValue/{name}/{surname}")] Adding route attribute also works for me.
Can we enable the query string routing on Global level, like in Startup.cs?
In .Net Core 5, the querystring path is not working correctly. I am getting default values (i.e. empty strings) on the query string path

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.