【发布时间】:2016-04-15 10:34:00
【问题描述】:
我有一个language 参数需要发送到我的文档端点。所以我必须验证用户是否在他的 GET 请求中发送了这个参数。
在我的模型中制定规则没有做任何事情:
public function rules()
{
return [
[['language'], 'required'],
];
}
因为我已经尝试过这个:
1) 我已经创建了 ParamsValidator 类:
<?php
namespace app\modules\v1\components;
use yii\web\UnprocessableEntityHttpException;
use yii\base\Component;
use Yii;
/**
* Class that is responsible for validating input params.
*/
class ParamsValidator extends Component
{
public function validate($params)
{
if (!isset($params['language'])) {
throw new UnprocessableEntityHttpException("Language parameter is required");
}
}
}
我在我的控制器init() 方法中调用它的validate() 方法:
public function init()
{
$this->_params = Yii::$app->request->queryParams;
$validator = new ParamsValidator();
$validator->validate($this->_params);
}
还有这种工作。代码有效,但我得到了丑陋的回应。我得到的不是很好的 JSON 响应,而是像这样开始的一堆 html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Unprocessable entity (#422)</title>
<style>
body {
font: normal 9pt "Verdana";
color: #000;
background: #fff;
}
我想要一些不错的 JSON 响应,而不是这个 html:
{
"name": "Forbidden",
"message": "You are not authorized to do this.",
"code": 0,
"status": 403,
"type": "yii\\web\\ForbiddenHttpException"
}
您看到的这个漂亮的 JSON 错误是由:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => [$this, 'authenticate']
];
但显然我的验证器没有这样做。
问题:
1) 如何验证来自 GET 请求的参数?
2) 如果我的方法是正确的,如何得到这个漂亮的 JSON 错误响应?
【问题讨论】:
标签: json rest validation get yii2