我很好奇你是否可以重载控制器方法在ASP。净MVC。每当我尝试时,都会得到下面的错误。这两个方法接受不同的参数。这是做不到的事情吗?
当前对控制器类型“MyController”上的动作“MyMethod”的请求在以下动作方法之间是不明确的:
我很好奇你是否可以重载控制器方法在ASP。净MVC。每当我尝试时,都会得到下面的错误。这两个方法接受不同的参数。这是做不到的事情吗?
当前对控制器类型“MyController”上的动作“MyMethod”的请求在以下动作方法之间是不明确的:
当前回答
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.
其他回答
如果这是尝试对几个视图使用一个GET操作,这些视图POST到不同模型的几个操作,那么尝试为每个POST操作添加一个GET操作,重定向到第一个GET,以防止刷新时出现404。
可能性不大,但很常见。
据我所知,你只能有相同的方法时,使用不同的http方法。
i.e.
[AcceptVerbs("GET")]
public ActionResult MyAction()
{
}
[AcceptVerbs("POST")]
public ActionResult MyAction(FormResult fm)
{
}
我在申请的时候也遇到过同样的问题。没有Modifiyig任何方法信息,我已经提供了[ActionName(“SomeMeaningfulName”)]在动作头部。问题解决
[ActionName("_EmployeeDetailsByModel")]
public PartialViewResult _EmployeeDetails(Employee model)
{
// Some Operation
return PartialView(model);
}
}
[ActionName("_EmployeeDetailsByModelWithPagination")]
public PartialViewResult _EmployeeDetails(Employee model,int Page,int PageSize)
{
// Some Operation
return PartialView(model);
}
是的。我已经能够通过为每个控制器方法设置HttpGet/HttpPost(或等效的AcceptVerbs属性)来做到这一点,即HttpGet或HttpPost,但不是两者都有。这样它就可以根据请求的类型来判断使用哪个方法。
[HttpGet]
public ActionResult Show()
{
...
}
[HttpPost]
public ActionResult Show( string userName )
{
...
}
我的一个建议是,对于这种情况,应该有一个私有实现,你的两个公共Action方法都依赖于它,以避免重复代码。
您可以使用[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");
}
}