Attempting to encode json and receive 400: Bad Request
in yii2
. I am trying to encode in Rest client but it is not working properly.
Solution 1: In case if all your controller's actions will deliver json you may also consider extanding yii\rest\Controller instead of yii\web\Controller :
namespace app\controllers;
use Yii;
class UserController extends \yii\rest\Controller
{
public function actionRegister()
{
$username = Yii::$app->request->post('username');
return $username;
}
}
NOTE: you may also use ActiveController which extends yii\rest\Controller (see rest docs) if you need to handle CRUD operations.
Solution 2: A different approach when extending yii\web\Controller is by using yii\filters\ContentNegotiator. Note that setting $enableCsrfValidation
to false may be mandatory here as it is explained in its related docs :
Whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to true. When CSRF validation is enabled, forms submitted to an Yii Web application must be originated from the same application. If not, a 400 HTTP exception will be raised.
Note, this feature requires that the user client accepts cookie. Also, to use this feature, forms submitted via POST method must contain a hidden input whose name is specified by $csrfParam. You may use yii\helpers\Html::beginForm() to generate his hidden input.
The above code may be rewritten this way :
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\ContentNegotiator;
use yii\web\Response;
class UserController extends Controller
{
public $enableCsrfValidation = false;
public function behaviors()
{
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
'only' => ['register'],
],
];
}
public function actionRegister()
{
$username = Yii::$app->request->post('username');
return $username;
}
}