繁体   English   中英

如果异常发生,Cakephp 3重定向不起作用

[英]Cakephp 3 redirect not working if exception is after

我在控制器中有一个动作,我调用一个函数检查是否设置了cookie,如果没有设置cookie,那么它应该重定向到其他地方。

在同一个控制器中,我对某些变量进行了评估,如果它们没有设置则抛出一个禁止的异常,但即使没有设置cookie,它也不会重定向,并且会出现禁止的消息

正确的操作应该是重定向的,并且在cookie不存在时或者至少我需要的时候从不评估变量。

这个函数在appController中

public function isCookieSet(){
  if(!$this->Cookie->check('cookie')){
    return $this->redirect($this->referer());
  }
}

和我的控制器内的代码

public function editarImg($negocio_id=null){    

    $this->isCookieSet(); //should redirect here

    //but executes until here
    if((!isset($this->perRol['crear_negocios']) || $this->perRol['crear_negocios']==0) || 
      (!isset($this->perRol['cargar_elim_imagenes']) || $this->perRol['cargar_elim_imagenes']==0)){
      throw new ForbiddenException($this->getMensajeError(403));
    }

    ...
}

问题中的代码可以重写(为清楚起见),如下所示:

public function editarImg($negocio_id=null){    
    if(!$this->Cookie->check('cookie')){
        $this->redirect($this->referer());
    }

    // more code

忽略对redirect的调用的返回值, 始终执行“更多代码”。

这不是如何调用方法redirect ,如文档中所述 (强调添加):

该方法将返回具有适当标头集的响应实例。 您应该从操作中返回响应实例以防止视图呈现,并让调度程序处理实际的重定向。

迁移指南中也提到这一点:

Cake\\Controller\\Controller::redirect()的签名已更改为Controller::redirect(string|array $url, int $status = null) 第三个参数$ exit已被删除。 该方法不再发送响应和退出脚本,而是返回具有适当标头集的Response实例。

代码示例

问题中的代码必须等同于:

public function editarImg($negocio_id=null){    
    if(!$this->Cookie->check('cookie')){
        return $this->redirect($this->referer()); # <- return the response object
    }

    // more code

试试这个,它应该工作:

public function isCookieSet(){
  if(!$this->Cookie->check('cookie')){

    // return $this->redirect($this->referer()); <- not working

    $this->response = $this->redirect($this->referer());
    $this->response->send();
    exit;

  }
}

暂无
暂无

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

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