Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use HttpGet Method with two different parameter value

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!

like image 679
Urgen Avatar asked Jan 29 '26 09:01

Urgen


1 Answers

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

like image 77
Nkosi Avatar answered Jan 31 '26 00:01

Nkosi