【发布时间】:2014-07-23 04:08:59
【问题描述】:
我编写了一个 C# MVC5 Internet 应用程序,并且对同一控制器中的两个 ActionResult 方法有疑问。
我有两个 Index ActionResult 方法如下:
public async Task<ActionResult> Index()
public async Task<ActionResult> Index(int? mapCompanyId)
我想浏览 Index() 方法或 Index(int? mapCompanyId) 方法,具体取决于是否为 mapCompanyId 指定了值。
目前,我收到此错误:
The current request for action 'Index' on controller type 'MapLocationController' is ambiguous between the following action methods:
System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Index() on type CanFindLocation.Controllers.MapLocationController
System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Index(System.Nullable`1[System.Int32]) on type CanFindLocation.Controllers.MapLocationController
我可以重写我的代码,以便只有一个 Index ActionResult,但如果可能的话,我宁愿有两个。
是否可以有两个同名的ActionResult,根据是否指定值,执行相关的ActionResult。如果是这样,是不是很容易实现,还是不值得花时间?
【问题讨论】:
-
MVC 将
int?解释为可选变量(否则如何通过 GET 将 int 设置为 null?)。因此,如果您没有指定mapCompanyId,那么您有两种匹配的方法是正确的。解决此问题的方法是在第二种方法中简单地将mapCompanyId设置为必需变量,只需将其更改为public async Task<ActionResult> Index(int mapCompanyId)。 MVC 不会混淆使用哪个。 -
@Aron 即使您将整数 non-nullable,它仍然会导致模棱两可的异常。事实上,框架无法根据导致问题的 HTTP 动词确定选择哪种方法。
-
@JustinHelgerson 听起来很像 ASP.Net Web API 而不是 MVC。 MVC 允许按动词过滤,仅此而已。而 Web API 完全适用于动词。
-
@Aron 我在评论之前测试了它。 :) 这里是测试代码:pastebin.com/ZdYf3sYk.
标签: c# controller polymorphism asp.net-mvc-5 actionresult