加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何在.net mvc中使用私有操作方法?

发布时间:2020-12-16 07:06:14 所属栏目:asp.Net 来源:网络整理
导读:我怎样才能在控制器中使用私有动作方法?当我使用私人方法时,它是无法访问的.它会因“未找到资源”而引发错误. private ActionResult Index() { return View(); } 解决方法 您可以使用私有/受保护的ActionResult在公共操作之间共享逻辑. private ActionResul
我怎样才能在控制器中使用私有动作方法?当我使用私人方法时,它是无法访问的.它会因“未找到资源”而引发错误.

private ActionResult Index()
                {
                    return View();
                }

解决方法

您可以使用私有/受保护的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
}

在控制器中使用非公共代码是很常见的,并且自动路由所有方法会违反预期行为并增加攻击足迹.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读