如何在yii2中进行Json编码?
尝试对 json 进行编码并在 yii2
中接收 400: Bad Request
.我正在尝试在 Rest 客户端中编码,但无法正常工作.
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.
<?php
namespace appcontrollers;
use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use appmodelsTblUserRegistration;
class UserController extends Controller
{
public function actionRegister()
{
$model = new TblUserRegistration();
$username = $_POST['username'];
echo json_encode($username);
}
}
?>
错误图片.
错误图片
推荐答案
解决方案 1: 如果您的控制器的所有操作都将传递 json,您也可以考虑扩展 yiiestController 而不是 yiiwebController :
Solution 1: In case if all your controller's actions will deliver json you may also consider extanding yiiestController instead of yiiwebController :
namespace appcontrollers;
use Yii;
class UserController extends yiiestController
{
public function actionRegister()
{
$username = Yii::$app->request->post('username');
return $username;
}
}
注意:您也可以使用 ActiveController它扩展了 yiiestController(参见 rest docs) 如果你需要处理 CRUD 操作.
NOTE: you may also use ActiveController which extends yiiestController (see rest docs) if you need to handle CRUD operations.
解决方案 2: 扩展 yiiwebController 是通过使用 yiifilters内容协商器.请注意,此处将 $enableCsrfValidation
设置为 false 可能是强制性的,因为它的 相关文档 :
Solution 2: A different approach when extending yiiwebController is by using yiifiltersContentNegotiator. Note that setting $enableCsrfValidation
to false may be mandatory here as it is explained in its related docs :
是否启用 CSRF(跨站点请求伪造)验证.默认为真.当启用 CSRF 验证时,表单提交到Yii Web 应用程序必须源自同一个应用程序.否则,将引发 400 HTTP 异常.
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.
注意,此功能需要用户客户端接受cookie.还,要使用此功能,通过 POST 方法提交的表单必须包含一个名称由 $csrfParam 指定的隐藏输入.您可以使用yiihelpersHtml::beginForm() 生成他的隐藏输入.
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 yiihelpersHtml::beginForm() to generate his hidden input.
上面的代码可以这样改写:
The above code may be rewritten this way :
namespace appcontrollers;
use Yii;
use yiiwebController;
use yiifiltersContentNegotiator;
use yiiwebResponse;
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;
}
}
相关文章