在beforeAction中判断用户是否登录,如果未登录则执行redirect方法跳转,但实际上并没有!
//初始化 public function beforeAction($action) { $this->USER_INFO = Users::isLogin(); if(Yii::$app->controller->id != 'login' && empty($this->USER_INFO)) { return $this->redirect(['login/index','referrer'=>Yii::$app->request->getHostInfo().Yii::$app->request->url]); } return parent::beforeAction($action); } //跳转 public function redirect($url = '',$statusCode = 302) { if(empty(Yii::$app->request->get('referrer',null)) && empty($url)) { $url = Yii::$app->request->getReferrer(); } else if(!empty(Yii::$app->request->get('referrer',null)) && empty($url)){ $url = Yii::$app->request->get('referrer',null); } return parent::redirect($url,$statusCode); }
解决方法是添加send()方法:
$this->redirect(['login/index','referrer'=>Yii::$app->request->getHostInfo().Yii::$app->request->url])->send();
手动向客户端发送请求:
/** * Sends the response to the client. */ public function send() { if ($this->isSent) { return; } $this->trigger(self::EVENT_BEFORE_SEND); $this->prepare(); $this->trigger(self::EVENT_AFTER_PREPARE); $this->sendHeaders(); $this->sendContent(); $this->trigger(self::EVENT_AFTER_SEND); $this->isSent = true; }