2012-06-11 25 views
2

我目前正在從我的Zend MVC應用程序構建一個控制器,該應用程序只能用作json服務來填充頁面。我想限制用戶只使用GET方法來訪問這個端點(出於一些安全原因)。Zend _forward()在preDispatch()中不起作用?

我關注了這個帖子_forward() in Zend does not work?但無法正常工作。

我正在使用preDispatch來檢測未得到的請求,並且想要在同一控制器中轉發到errorAction。我的代碼看起來像這

public function preDispatch(){ 
    $this->_helper->layout()->disableLayout(); 
    $this->_helper->viewRenderer->setNoRender(); 
    //Restrict this Controller access to Http GET method 
    if(!($this->getRequest()->isGet())){ 
     return $this->_forward('error'); 
    } 
} 

public function errorAction(){ 
    $this->getResponse()->setHttpResponseCode(501); 
    echo "Requested Method is not Implemented"; 
} 

當我測試的頁面與一個POST請求,它會拋出

PHP Fatal error: Maximum execution time of 30 seconds exceeded

我得到了它與

$this->_redirect("service/error"); 

工作想知道,如果它是唯一的/處理這種情況的最佳方法。

任何幫助將非常感激。提前致謝。

回答

2

調用_forward不起作用的原因是因爲請求方法沒有更改,因此您最終處於無限循環嘗試轉向error操作,因爲請求始終爲POST

_forward通過修改調度請求時將調用的模塊,控制器和操作來工作,_redirect實際上返回302重定向並導致瀏覽器發出額外的HTTP請求。

兩種方法都可以,但我寧願去_forward,因爲它不需要額外的HTTP請求(但你仍然保證POST請求被拒絕)。

此代碼應爲你工作:

if(!($this->getRequest()->isGet())){ 
     // change the request method - this only changes internally 
     $_SERVER['REQUEST_METHOD'] = 'GET'; 

     // forward the request to the error action - preDispatch is called again 
     $this->_forward('error'); 

     // This is an alternate to using _forward, but is virtually the same 
     // You still need to override $_SERVER['REQUEST_METHOD'] to do this 
     $this->getRequest() 
      ->setActionName('error') 
      ->setDispatched(false); 
    } 
+0

真棒......工作就像一個魅力..!感謝您的快速回應:D –