我想加密REST-Request的响应流。我从数据库中获取数据并将其作为xml(actionAll)返回。这很好用。然后我添加了一个在响应发送到客户端之前执行的eventHandler(beforeAction)。这也有效。我的问题是,当eventHandler调用它时, encryptResponse - 方法中的 $ response 不包含任何数据。变量content,data和stream在response-object中始终为null。
感谢您的帮助!
<?php
namespace app\controllers;
use Yii;
use app\models\Order;
use yii\filters\auth\HttpBasicAuth;
use yii\web\Response;
use app\models\User;
class OrderController extends \yii\rest\Controller{
/**
* disable session for REST-Request
* no loginUrl required
*/
public function init(){
parent::init();
\Yii::$app->user->enableSession = false;
\Yii::$app->user->loginUrl = null;
}
/**
* HttpBasicAuth for authentication
*/
public function behaviors(){
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => function ($username, $password) {
if($username==\Yii::$app->params['HttpBasicAuth']['username'] && $password==\Yii::$app->params['HttpBasicAuth']['password']){
return new User();
}else{
return null;
}
}];
return $behaviors;
}
/**
* set response-format to xml
* fetch data from db
*
*/
public function actionAll(){
\Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
$models = Order::find()->all();
return $models;
}
/**
* hook into action and add event handler
*/
public function beforeAction($action){
$response = Yii::$app->getResponse();
$response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);
}
/**
* callback for event-handler
*/
public function encryptResponse(){
$response = Yii::$app->getResponse();
var_dump($response);
}
}
答案 0 :(得分:2)
您可以在init中设置响应事件。
或者您只需在return true
函数中添加beforeAction
,否则数据将为null
,因为未调用该操作,Yii2 docs {{ 3}}
use Yii;
...
public function init()
{
parent::init();
Yii::$app->user->enableSession = false;
Yii::$app->user->loginUrl = null;
Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);
}
public function beforeAction($action)
{
$response = Yii::$app->getResponse();
$response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);
return true; // << required
}