解决ThinkPHP6公共控制器Base无法使用redirect()重定向问题

2020-09-08   阅读:4013   分类:后端    标签: TP6

在做角色权限或者登录的时候我们需要判断是否登录,这时我们可能会用到重定向跳转,但是你会发现TP6下构造方法下是无法重定向的,这是为何呢?

1、原因

这不是ThinkPHP6的BUG,这个问题不是BUG的原因是什么?原因是redirect()返回的是\think\response\Redirect对象,而此对象被app\BaseController类中的构造方法所获取。

vendor/topthink/framework/src/helper.php

if (!function_exists('redirect')) {
    /**
     * 获取\think\response\Redirect对象实例
     * @param string $url  重定向地址
     * @param int    $code 状态码
     * @return \think\response\Redirect
     */
    function redirect(string $url = '', int $code = 302): Redirect
    {
        return Response::create($url, 'redirect', $code);
    }
}

2、解决无法使用redirect()重定向问题,我们可以重写重定向方法,在Base控制器下加入以下方法

    /**
     * 自定义重定向方法
     * @param $args
     */
    public function redirectTo(...$args)
    {
        // 此处 throw new HttpResponseException 抛出异常重定向
        throw new HttpResponseException(redirect(...$args));
    }

3、使用方法

return $this->redirectTo((string)url('admin/Login/index'));

综上,这样就能解决了ThinkPHP6无法重定向跳转问题


【腾讯云】 爆款2核2G3M云服务器首年 61元,2核2G4M云服务器新老同享 99元/年,续费同价

‘简忆博客’微信公众号 扫码关注‘简忆博客’微信公众号,获取最新文章动态
转载:请说明文章出处“来源简忆博客”。http://tpxhm.com/adetail/415.html

×
觉得文章有用就打赏一下文章作者
微信扫一扫打赏 微信扫一扫打赏
支付宝扫一扫打赏 支付宝扫一扫打赏

文章评论(0)

登录
简忆博客壁纸一
简忆博客壁纸二
简忆博客壁纸三
简忆博客壁纸四
简忆博客壁纸五
简忆博客壁纸六
简忆博客壁纸七
简忆博客壁纸八
头像

简忆博客
勤于学习,乐于分享

置顶推荐

打赏本站

如果你觉得本站很棒,可以通过扫码支付打赏哦!
微信扫码:你说多少就多少~
微信扫码
支付宝扫码:你说多少就多少~
支付宝扫码
×