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

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


当前回答

抱歉耽搁了。我也遇到过同样的问题,我找到了一个有很好的答案的链接,可以帮助新人

所有的功劳为BinaryIntellect网站和作者

基本上,有四种情况:使用不同的动词、使用路由、使用[NoAction]属性进行重载标记以及使用[ActionName]更改操作属性名称。

这取决于你的需求和你的情况。

无论如何,请点击以下链接:

链接: http://www.binaryintellect.net/articles/8f9d9a8f-7abf-4df6-be8a-9895882ab562.aspx

其他回答

将基方法创建为virtual

public virtual ActionResult Index()

将被覆盖的方法创建为override

public override ActionResult Index()

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

不,不,不。去试试下面的控制器代码,在这里我们重载了“LoadCustomer”。

public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult LoadCustomer()
        {
            return Content("LoadCustomer");
        }
        public ActionResult LoadCustomer(string str)
        {
            return Content("LoadCustomer with a string");
        }
    }

如果您尝试调用“LoadCustomer”操作,您将得到如下图所示的错误。

多态性是c#编程的一部分,而HTTP是一种协议。HTTP不理解多态性。HTTP工作在概念或URL和URL只能有唯一的名称。因此HTTP不实现多态性。

为了解决这个问题,我们需要使用“ActionName”属性。

public class CustomerController : Controller
    {
        //
        // GET: /Customer/

        public ActionResult LoadCustomer()
        {
            return Content("LoadCustomer");
        }

        [ActionName("LoadCustomerbyName")]
        public ActionResult LoadCustomer(string str)
        {
            return Content("LoadCustomer with a string");
        }
    }

因此,现在如果你调用URL“客户/LoadCustomer”,“LoadCustomer”动作将被调用,URL结构“客户/LoadCustomerByName”,“LoadCustomer(字符串str)”将被调用。

上面的答案我已经从这篇codeproject文章——> MVC动作重载

您可以使用[ActionName("NewActionName")]来使用不同名称的相同方法:

public class HomeController : Controller
{
    public ActionResult GetEmpName()
    {
        return Content("This is the test Message");
    }

    [ActionName("GetEmpWithCode")]
    public ActionResult GetEmpName(string EmpCode)
    {
        return Content("This is the test Messagewith Overloaded");
    }
}

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.

你可以使用一个ActionResult来处理Post和Get:

public ActionResult Example() {
   if (Request.HttpMethod.ToUpperInvariant() == "GET") {
    // GET
   }
   else if (Request.HttpMethod.ToUpperInvariant() == "POST") {
     // Post  
   }
}

如果您的Get和Post方法具有匹配的签名,则非常有用。