gpt4 book ai didi

redirect - init 中的 yii2 重定向是否有效?

转载 作者:行者123 更新时间:2023-12-03 06:42:53 24 4
gpt4 key购买 nike

class TestController extends Controller {
function init() {
if(!(strtolower(yii::$app->requestedRoute) == "account/login" || empty(yii::$app->requestedRoute)))
{
if (false===$this->isLogin()) {

return $this->redirect('/login'); //it works, will redirect

}
} else {
if($this->isLogin()) {
return $this->redirect('/purchaser/manifest'); //not work, won't redirect
//echo $this->redirect('/purchaser/manifest'); //work


}
}
}
}

我已经覆盖了 Controller 。当我尝试做过滤时,我发现了这个问题。我很困惑,有什么帮助吗?

最佳答案

来自 Yii2 文档:

In case the action should not run, the request should be handled inside of the beforeAction code by either providing the necessary output or redirecting the request. Otherwise the response will be empty.

public function beforeAction($action)
{
if (!parent::beforeAction($action)) {
return false;
}
// your custom code here
//Eg
if(something){
$this->redirect('/login');
return false; //not run the action
}

return true; // continue to run action
}

Yii2 不关心 init() 函数的返回值。应用程序仍将继续运行操作。关于 redirect() 函数,只有在应用程序完成(beforeAction 返回 false 或操作返回)后,它才会起作用。因此,当您在 init() 函数中调用 redirect() 时,什么也不会发生。
但是 return $this->redirect('/login'); 它有效。为什么?因为在这种情况下,应用程序会在运行您的操作后重定向。
你可以尝试,甚至写 $this->redirect('/login'); 它仍然有效。

关于redirect - init 中的 yii2 重定向是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31382862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com