【问题标题】:MVC5 ambiguous action methods in controller控制器中的MVC5模棱两可的动作方法
【发布时间】: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&lt;ActionResult&gt; 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


【解决方案1】:

这是不可能的,因为您正在尝试为每个方法执行 GET 请求。 ASP.NET MVC 操作选择器不知道选择哪种方法。

如果有意义并且您可以使用HttpGetHttpPost 属性来区分每种类型的HTTP 请求的方法。在您的情况下,这听起来没有意义。

【讨论】:

    【解决方案2】:

    您可以像这样为动作重载分配不同的 HTTP 方法:

    [HttpGet]
    public async Task<ActionResult> Index()
    
    [HttpPost]
    public async Task<ActionResult> Index(int? mapCompanyId)
    

    MVC 运行时将能够根据请求 HTTP 方法选择适当的操作。

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 2010-11-11
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      相关资源
      最近更新 更多