我很好奇你是否可以重载控制器方法在ASP。净MVC。每当我尝试时,都会得到下面的错误。这两个方法接受不同的参数。这是做不到的事情吗?

当前对控制器类型“MyController”上的动作“MyMethod”的请求在以下动作方法之间是不明确的:


当前回答

如果您希望代码进行重载,可以使用该属性。

[ActionName("MyOverloadedName")]

但是,您必须为相同的http方法使用不同的操作名称(正如其他人所说)。所以这只是语义上的。您希望在代码中使用名称还是属性中使用名称?

Phil有一篇相关的文章:http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx

其他回答

为了克服这个问题,你可以编写一个ActionMethodSelectorAttribute来检查每个动作的MethodInfo,并将其与发布的表单值进行比较,然后拒绝任何与表单值不匹配的方法(当然,不包括按钮名称)。

举个例子:- http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/

但是,这不是一个好主意。

如果这是尝试对几个视图使用一个GET操作,这些视图POST到不同模型的几个操作,那么尝试为每个POST操作添加一个GET操作,重定向到第一个GET,以防止刷新时出现404。

可能性不大,但很常见。

This answer for those who struggling with the same issue. You can implement your own custom filter based on ActionMethodSelectorAttribute. Here I found the best solution for solving your question. Works fine on .net 5 project. If you try to implement the same logic as was in web api controllers then use Microsoft.AspNetCore.Mvc.WebApiCompatShim. This nuget package provides compatibility in ASP.NET Core MVC with ASP.NET Web API 2 to simplify migration of existing Web API implementations. Please check this answer but consider that starting with ASP.NET Core 3.0, the Microsoft.AspNetCore.Mvc.WebApiCompatShim package is no longer available.

将基方法创建为virtual

public virtual ActionResult Index()

将被覆盖的方法创建为override

public override ActionResult Index()

编辑:这显然只适用于当override方法在一个派生类中,而这似乎不是OP的意图。

我需要一个过载:

public ActionResult Index(string i);
public ActionResult Index(int groupId, int itemId);

很少有足够的争论,我最终这样做:

public ActionResult Index(string i, int? groupId, int? itemId)
{
    if (!string.IsNullOrWhitespace(i))
    {
        // parse i for the id
    }
    else if (groupId.HasValue && itemId.HasValue)
    {
        // use groupId and itemId for the id
    }
}

这不是一个完美的解决方案,尤其是当你有很多争论的时候,但它对我来说很有效。