Can I use several retrieval methods in ASP.Net Web API controller

I want to implement several Get methods for Ex:

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

Is it possible to implement this, I do not want to change the name of the action method, since in this case I need to enter the name of the action in the URL.

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

+5
source share
2 answers

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

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

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

Hope this helps.

+6
source

You need to add an action to the route template in order to implement several GET methods in the 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 name of the action / method should begin with Get , orelse you need to specify [HttpGet] over the action / method

+3
source

Source: https://habr.com/ru/post/1207021/


All Articles