[英]Can I have Multiple Get Methods in ASP.Net Web API controller
I want to implement multiple Get Methods, for Ex: 我想为Ex实现多个Get方法:
Get(int id,User userObj) and Get(int storeId,User userObj) 获取(int id,User userObj)和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. 是否可以像这样实现,我不想更改操作方法名称,因为在这种情况下我需要在URL中键入操作名称。
I am thinking of hitting the action methods through this sample format ' //localhost:2342/ ' which does not contains action method name. 我正在考虑通过这个样本格式' // localhost:2342 / '命中动作方法,它不包含动作方法名称。
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. 基本上你不能这样做,原因是两个方法都有相同的名称和完全相同的签名(相同的参数号和类型),这不会用C#编译,因为C#不允许这样做。
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. 现在,使用Web API,如果您有两个方法具有相同的操作,例如您的示例(两个GET),并且具有相同的签名(int,User),当您尝试从客户端命中其中一个时(如来自Javascript) )ASp.NET将尝试将传递的参数类型与方法(动作)进行匹配,因为两者都具有确切的签名,它将失败并引发有关歧义的异常。
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. 因此,您可以将ActionName属性添加到方法中以区分它们,或者使用Route属性并为方法指定不同的路径。
Hope that helps. 希望有所帮助。
You need to add action name to the route template to implement multiple GET methods in ASP.Net Web API controller . 您需要在路由模板中添加操作名称,以在ASP.Net Web API控制器中实现多个GET方法。
WebApiConfig: 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 注意:动作/方法名称应以' Get '开头,您需要在动作/方法上方指定[HttpGet]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.