4

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 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Where do I add this ? my ApiController doesnt have attributes
Use the attribute in your GetTall() method. See the updated answer.
I am getting the following error: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'RESTServices.Controllers.recordsController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
It's an empty controller, whatever comes as default with ASP.NET webapi.
Probably you are calling the Get(int id) method without passing a integer value. The call should be like "localhost/records/123" where 123 is an id.
|
0

See here: https://learn.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) { ... }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.