在单独的action中关闭csrf验证

新建一个Behavior

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
use ;
use yiibaseActionEvent;
use yiibaseBehavior;
use yiiwebController;
class NoCsrf extends Behavior
{
public $actions = [];
public $controller;
public function events()
{
return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
}
public function beforeAction($event)
{
$action = $event->action->id;
if(in_array($action, $this->actions)){
$this->controller->enableCsrfValidation = false;
}
}
}

Controller中添加Behavior

1
2
3
4
5
6
7
8
9
10
11
12
13
 
public function behaviors()
{
return [
'csrf' => [
'class' => NoCsrf::className(),
'controller' => $this,
'actions' => [
'action-name'
]
]
];
}

这样就实现了在action中关闭Csrf而不是在整个Controller中关闭。