Yii2 - How to solve Bad Request (# 400) Can't verify the sending of data?

I have a controller created by Gii. I change the behavior this way:

public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, 'roles' => ['@'], ], ], ], ]; } 

When I fill out a form and submit it, sometimes I get an error

Bad Request (#400) Unable to verify your data submission

But if I click the back button in my browser and submit the form with the same value again, everything will be fine if it is submitted successfully.

I searched on google and stackoverflow, many of them say that the problem is with the CSRF token. But in my layout I put <?= Html::csrfMetaTags() ?> , And in my form there is <input type="hidden" name="_csrf" value="...">

Can anyone help me solve this problem? And explain why this is happening?

+6
source share
2 answers

add to form

 <input type="hidden" name="_csrf" value="<?=Yii::$app->request->getCsrfToken()?>" /> 
+3
source

I had the same problem and ended up disabling csrf checking.

 public function actionCreate() { Yii::$app->controller->enableCsrfValidation = false; } 

It seemed to me to me.

-2
source

All Articles