我很好奇你是否可以重载控制器方法在ASP。净MVC。每当我尝试时,都会得到下面的错误。这两个方法接受不同的参数。这是做不到的事情吗?
当前对控制器类型“MyController”上的动作“MyMethod”的请求在以下动作方法之间是不明确的:
我很好奇你是否可以重载控制器方法在ASP。净MVC。每当我尝试时,都会得到下面的错误。这两个方法接受不同的参数。这是做不到的事情吗?
当前对控制器类型“MyController”上的动作“MyMethod”的请求在以下动作方法之间是不明确的:
当前回答
不,不,不。去试试下面的控制器代码,在这里我们重载了“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动作重载
其他回答
不,不,不。去试试下面的控制器代码,在这里我们重载了“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动作重载
据我所知,你只能有相同的方法时,使用不同的http方法。
i.e.
[AcceptVerbs("GET")]
public ActionResult MyAction()
{
}
[AcceptVerbs("POST")]
public ActionResult MyAction(FormResult fm)
{
}
你还可以这么做……您需要一个能够有参数而没有参数的方法。
为什么不试试这个……
public ActionResult Show( string username = null )
{
...
}
这对我很有效……在这个方法中,你可以测试是否有传入参数。
已更新以删除字符串上无效的nullable语法并使用默认参数值。
将基方法创建为virtual
public virtual ActionResult Index()
将被覆盖的方法创建为override
public override ActionResult Index()
编辑:这显然只适用于当override方法在一个派生类中,而这似乎不是OP的意图。
是的。我已经能够通过为每个控制器方法设置HttpGet/HttpPost(或等效的AcceptVerbs属性)来做到这一点,即HttpGet或HttpPost,但不是两者都有。这样它就可以根据请求的类型来判断使用哪个方法。
[HttpGet]
public ActionResult Show()
{
...
}
[HttpPost]
public ActionResult Show( string userName )
{
...
}
我的一个建议是,对于这种情况,应该有一个私有实现,你的两个公共Action方法都依赖于它,以避免重复代码。