I am trying to support multiple Get() methods per controller, as well as just specially named methods accessible through web api. I have done this in MVC 5, but can't seem to figure out how it is done in MVC 6. Any ideas? Thanks.
As mentioned, Web API controller can include multiple Get methods with different parameters and types.
You cannot have multiple Get methods with same url pattern. You can use attribute routing and setup multiple GET method's for different url patterns.
[Route("api/[controller]")]
public class IssuesController : Controller
{
// GET: api/Issues
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "item 1", "item 2" };
}
// GET api/Issues/5
[HttpGet("{id}")]
public string Get(int id)
{
return "request for "+ id;
}
// GET api/Issues/special/5
[HttpGet("special/{id}")]
public string GetSpecial(int id)
{
return "special request for "+id;
}
// GET another/5
[HttpGet("~/another/{id}")]
public string AnotherOne(int id)
{
return "request for AnotherOne method with id:" + id;
}
// GET api/special2/5
[HttpGet()]
[Route("~/api/special2/{id}")]
public string GetSpecial2(int id)
{
return "request for GetSpecial2 method with id:" + id;
}
}
You can see that i used both HttpGet
and Route
attributes for defining the route patterns.
With the above configuration, you you will get the below responses
Request Url : yourSite/api/issues/
Result ["value1","value2"]
Request Url : yourSite/api/issues/4
Result request for 4
Request Url : yourSite/api/special2/6
Result request for GetSpecial2 method with id:6
Request Url : yourSite/another/3
Result request for AnotherOne method with id:3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With