6

I want to implement multiple Get Methods, for Ex:

Get(int id,User userObj) and Get(int storeId,User userObj)

Is it possible to implement like this, I don't want to change action method name as in that case I need to type action name in URL.

I am thinking of hitting the action methods through this sample format '//localhost:2342/' which does not contains action method name.

2
  • 2
    Forget that they are action methods for a second. You can't have those two methods in a class, period. They have the same signatures Commented Nov 17, 2014 at 11:12
  • see this - stackoverflow.com/questions/15620142/… Commented Nov 17, 2014 at 11:13

2 Answers 2

7

Basically you cannot do that, and the reason is that both methods have same name and exactly the same signature (same parameter number and types) and this will not compile with C#, because C# doesn't allow that.

Now, with Web API, if you have two methods with the same action like your example (both GET), and with the same signature (int, User), when you try to hit one of them from the client side (like from Javascript) the ASp.NET will try to match the passed parameters type to the methods (actions) and since both have the exact signature it will fail and raise exception about ambiguity.

So, you either add the ActionName attribute to your methods to differentiate between them, or you use the Route Attribute and give your methods a different routes.

Hope that helps.

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

Comments

3

You need to add action name to the route template to implement multiple GET methods in ASP.Net Web API controller.

WebApiConfig:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new {id = RouteParameter.Optional }
);  

Controller:

public class TestController : ApiController
{
     public DataSet GetStudentDetails(int iStudID)
     {

     }

     [HttpGet]
     public DataSet TeacherDetails(int iTeachID)
     {

     }
}

Note: The action/method name should startwith 'Get', orelse you need to specify [HttpGet] above the action/method

2 Comments

Why do you show the default route configuration as a solution?
Bad vote-down. The default WebAPI route config has no action param by default, just "api/{controller}/{id}". Adding {action} actually allows for multiple GET methods, which is what the OP wanted.

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.