[英]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.