我可以在ASP.Net的Web API控制器多个GET方法 [英] Can I have Multiple Get Methods in ASP.Net Web API controller

查看:380
本文介绍了我可以在ASP.Net的Web API控制器多个GET方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现多找方法,例如:

I want to implement multiple Get Methods, for Ex:

获取(INT ID,用户userObj)获取(INT STOREID,用户userObj)

是否有可能实现这样的,我并不想改变操作方法的名称在这种情况下,我需要在URL输入操作名称。

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.

我想通过这个样本格式击球的动作方法 //本地主机:2342 /
其中不包含动作方法的名字。

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

推荐答案

基本上你不能这样做,原因是这两种方法都有相同的名称和完全相同的签名(相同的参数数量和类型),这不会编译用C#,因为C#不允许。

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.

现在,通过Web API,如果你有两个方法,像你的例子同样的动作(同时支持GET),并具有相同签名(INT,用户),当您试图打他们一个从客户端(像从Javascript)的ASp.NET将尝试匹配传递的参数类型的方法(行动),并因为两者有确切的签名会失败,并提高对歧义例外。

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.

所以,你要么ActionName属性添加到您的方法来区分它们,或者你使用Route属性,给你的方法不同的路线。

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.

希望有所帮助。

这篇关于我可以在ASP.Net的Web API控制器多个GET方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆