Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query string and attribute routing together for controller .NET core web API

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
like image 226
NETGeek Avatar asked Jan 27 '23 10:01

NETGeek


1 Answers

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.

like image 176
Marcus Höglund Avatar answered Feb 01 '23 19:02

Marcus Höglund