2

我目前正在从我的 Zend MVC 应用程序构建一个控制器,它只能用作 json 服务来填充页面。我想限制用户只使用 GET 方法来访问这个端点(出于某些安全原因)。

在 Zend 中关注了这篇文章 _forward() 不起作用?但无法开始工作。

我正在使用 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";
}

当我使用发布请求测试页面时,它会抛出

PHP致命错误:超过30秒的最大执行时间

我得到了它的工作

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

想知道这是否是处理这种情况的唯一/最佳方法。

任何帮助将非常感激。提前致谢。

4

1 回答 1

2

The reason that calling _forward doesn't work is because the request method doesn't change so you end up in an infinite loop trying to forward to the error action since the request is always POST.

_forward works by modifying the module, controller, and action that will be called when the request is dispatched, _redirect actually returns a 302 redirect and results in an additional HTTP request by the browser.

Either method is okay, but I'd prefer to go with _forward since it won't require an additional HTTP request (but you still guarantee the POST request is denied).

This code should work for you:

    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);
    }
于 2012-06-11T18:35:32.880 回答