3
votes

So I am new to ASP.NET webAPI and I created a controller called: UsersController, which exposes the 4 CRUD methods. If the user calls:

GET/Users

  • this will use the default Get method

    public IEnumerable Get()

if the user calls:

GET /users/1234

  • this in turn will call:

    public string Get(int id)

BUT... what if I need something like:

GET / Users/Males

  • I want to return all male users and

GET /Users/Tall

  • I want to return all Tall users

how do I override/overload the GET method ?

2

2 Answers

0
votes

Use RouteAttribute.

In your Api Controller:

public IEnumerable Get()
{
}

public string Get(int id)
{
}

[Route("/Users/Tall")]
public IEnumerable GetTall()
{
}

More info about: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2.

0
votes

See here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Route Constraints Route constraints let you restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}". For example:

[Route("users/{id:int}")]
public User GetUserById(int id) { ... }

Route("users/{name}")]
public User GetUserByName(string name) { ... }