Search code examples
c#asp.netmodel-view-controllerapi-design

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


Solution

  • 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";
    }