dongluolie3487 2017-06-22 11:42
浏览 684
已采纳

在Yii2中使用控制器中的beforeAction()和behavior()方法

I want to use both beforeAction() and behaviors() method in my controller.

If i add beforeAction() method in my code than behaviors() method is not working.

And if i remove beforeAction() method than behaviors() method is working.

I dont want to remove beforeAction() as it is use to disable csrf token for ajax calls.

public function beforeAction($action)
{
  if($action->id =='ignore' || $action->id =='accept')
  {
    $this->enableCsrfValidation = false;
  }
  return true;
}

And i want to use behaviors() method for authentication.

public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['create','index','update','change','view','page','active','list'],
            'rules' => [
                [
                    'actions' => ['create','index','update','change','view','page','active','list'],
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function ($rule, $action)
                    {
                      echo "string";
                      die;
                    },
                ],
            ],
            'denyCallback' => function ($rule, $action) {
                return $this->redirect(Yii::$app->request->baseUrl);
            }
        ],
    ];
}

Is there any way to use both method in same controller.

  • 写回答

1条回答 默认 最新

  • dongxing8766 2017-06-22 11:54
    关注
    public function beforeAction($action)
    {
      if($action->id =='ignore' || $action->id =='accept')
      {
        $this->enableCsrfValidation = false;
      }
      //return true;
      return parent::beforeAction($action);
    }
    

    you need to return the parent beforeAction()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化