如果用户试图在没有适当凭证的情况下访问REST api,我的yii应用程序会在controller.php文件中抛出401错误,如下所示:
throw new UnauthorizedHttpException('Access unavailable without access_token.', 401);
返回如下格式的错误:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<name>Unauthorized</name><message>Access unavailable.</message>
<code>401</code>
<status>401</status>
<type>yii'web'UnauthorizedHttpException</type>
</response>
如何以JSON格式返回此错误?
{
"name": "Access unavailable.",
"message": "You are not authorized.",
"code": 0,
"status": 401
}
我的移动应用程序访问这个资源需要一个JSON对象
尝试在您的自定义__construct中返回或更好的上面添加这个。
Yii::$app->response->format = 'json';
yii2 rest控制器对"Accept" HTTP报头作出反应。如果在这个报头中只有"application/json"存在,那么rest控制器的答案将是json
这对我来说很有效。扩展activeController
,我把它放在api'controllers'ActiveController.php
namespace api'controllers;
class ActiveController extends yii'rest'ActiveController {
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => 'yii'filters'ContentNegotiator',
'formats' => [
'application/json' => 'yii'web'Response::FORMAT_JSON,
]
];
return $behaviors;
}
}
then in my controller
use api'controllers'ActiveController;
class blablaController extends ActiveController
{
...
}
现在在未经授权的情况下,我得到一个JSON而不是XML
{"success":false,"data":{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401}}