最近在开发功能中 发现redirect竟然不能正常跳转,查了好长时间,还以为写的代码有问题,主要是在beforeAction中做了是否登录的判断,未登录则跳转到登录页面,所有的类继承的这个baseController
public function beforeAction($action)
{
if(parent::beforeAction($action))
{
if ($action->controller->id == 'default' && in_array($action->id, array('login', 'logout'))) {
// 这里是不需要登陆验证的
if($action->id == 'login') {
$session = Yii::$app->session;
if($session['companyId'] && $session['companyName']) {
$action->controller->redirect(['default/index']);
}
}
} else {
$session = Yii::$app->session;
if(!$session['companyId'] || !$session['companyName']) {
$action->controller->redirect(['default/login']);
}
}
return true;
}
else
return false;
}
在正常情况下,使用 return $this->redirect($url);
解决方式一:在redirect后面使用send()
$this->redirect(登录页地址)->send();
$this->redirect(登录页地址l);Yii::$app->response->send();
解决方式二:
$this->redirect(登录页地址);
Yii::$app->end();
用\Yii::$app->end();\Yii::$app->response->send();不管在actionXXX还是init方法都能终止代码,而return只能在action终止代码,是因为在init()里仅仅是代码的执行,return只是代码返回。