簡體   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