简体   繁体   English

Yii2:如何在无效路由上重定向?

[英]Yii2: How to redirect on invalid routes?

Instead of showing an error page I'd like to redirect the user to the start page in general, if the route is invalid (there is no controller/action like requested). 我通常不将错误页面显示在错误页面上,而是将用户重定向到起始页面(如果路由无效)(没有类似请求的控制器/操作)。 To make it sound the redirection should only happen on 'normal' page requests. 为了使其听起来正确,重定向应该仅在“正常”页面请求上发生。 Though AJAX calls can be invalid as well, I don't want to send a redirect to the browser here. 尽管AJAX调用也可能无效,但我不想在此处向浏览器发送重定向。

How can I do this efficiently? 我如何有效地做到这一点?

You can override ErrorAction class and will implement necessary logic. 您可以重写ErrorAction类 ,并将实现必要的逻辑。 For example: 例如:

class MyErrorAction extends \yii\web\ErrorAction
{

    public $redirectRoute;  

    public function run()
    {
        if (!Yii::$app->getRequest()->getIsAjax()) {
            Yii::$app->getResponse()->redirect($this->redirectRoute)->send();
            return;
        }
        return parent::run();
    }
}

After it, you should add this action in a controller and configure it 之后,您应该在控制器中添加此操作并对其进行配置

class SiteController
{
    public function actions()
    {
        return [
            'error' => [
                'class' => MyErrorAction::class
                'redirectRoute' => 'site/my-page'
            ],
        ];
    }
}

and configure the route of error action in the error handler 并在错误处理程序中配置错误操作的路由

'errorHandler' => [
    'errorAction' => 'site/error',
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM