How do I implement following method? I have two HttpGet Methods with following parameter value:-
[HttpGet("{id}")] int value for route
[HttpGet("{slug}")] string value for route
Route looks like this on controller:-
[Route("api/[controller]")
Route configuration:-
app.UseMvc(routes =>
{
routes.MapRoute(
name: "defaultRoute",
template: "{controller=Posts}/{action=GetAsync}/{id?}");
});
How to make sure that specific HttpGet Method gets triggered based on route value. In the above case only HttpGet with {id} route is working. Latter only works if former does not exist/remove. How can I direct my route to a method with specific header value.
Thanks!
Use route constraints
[Route("api/[controller]")
public class ValuesController : Controller {
//GET api/values/1
[HttpGet("{id:int}")] //int value for route
public IActionResult GetById(int id) {
//...
}
//GET api/values/something-else
[HttpGet("{slug}")] //string value for route
public IActionResult Get(string slug) {
//...
}
}
Reference Routing in ASP.NET Core
Reference Routing to controller actions in ASP.NET Core
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