Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have both 'get by id' and 'get by name' routes on ASP.NET core 2.0 controller?

I'm writing a small Web API controller. Currently I've routed a

[HttpGet("{id}"}]

path and it works fine: localhost:8080/Controller/1 returns the item with the id equal to 1.

The problem is that I am trying to add a 'get by name' request:

[HttpGet("{name}")]

How can I go about doing this?

Thank you for your time

like image 464
Miguel Freitas Avatar asked Nov 01 '25 02:11

Miguel Freitas


1 Answers

In this exact example you can put in a route constraint indicating that id is an int. It should route correctly after that.

[HttpGet("{id:int}")]
public string GetById(int id)
{
   return id.ToString();
}

[HttpGet("{name}")]
public string GetByName(string name)
{
   return name + " name";
}
like image 177
stephen.vakil Avatar answered Nov 02 '25 17:11

stephen.vakil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!