Asp.net mvc 如何在.NETMVC中使用私有操作方法?
如何在控制器中使用私有操作方法?当我使用私有方法时,它是不可访问的。它抛出错误为“未找到资源”Asp.net mvc 如何在.NETMVC中使用私有操作方法?,asp.net-mvc,Asp.net Mvc,如何在控制器中使用私有操作方法?当我使用私有方法时,它是不可访问的。它抛出错误为“未找到资源” 您可以使用私有/受保护的ActionResult在公共操作之间共享逻辑 private ActionResult SharedActionLogic( int foo ){ return new EmptyResult(); } public ActionResult PublicAction1(){ return SharedActionLogic( 1 ); } public
您可以使用私有/受保护的
ActionResult
在公共操作之间共享逻辑
private ActionResult SharedActionLogic( int foo ){
return new EmptyResult();
}
public ActionResult PublicAction1(){
return SharedActionLogic( 1 );
}
public ActionResult PublicAction2(){
return SharedActionLogic( 2 );
}
但框架只会调用公共操作方法(参见下面的源代码)。这是故意的
从System.Web.Mvc中的内部类ActionMethodSelector:
private void PopulateLookupTables()
{
// find potential matches from public, instance methods
MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
// refine further if needed
MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);
// remainder of method omitted
}
控制器中通常有非公共代码,自动路由所有方法将违反预期行为并增加攻击足迹。将
ActionResult
设置为私有的目的是什么?我只想知道,是否有可能存在一个ActionResult
显式存在以将结果返回到框架;这是绝对没有意义的,因为它是私人的。。。还需要它做什么?只需尝试从公共操作返回私有操作,看看会发生什么:public ActionResult mypublic action(){return Index();}
。顺便说一句,上面所有的问题都非常可靠。理论上,我们可以使用一个私有方法返回ActionResult
,并在公共控制器操作中使用它来防止代码重复。
private void PopulateLookupTables()
{
// find potential matches from public, instance methods
MethodInfo[] allMethods = ControllerType.GetMethods(BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public);
// refine further if needed
MethodInfo[] actionMethods = Array.FindAll(allMethods, IsValidActionMethod);
// remainder of method omitted
}