Zend framework2 如何创建403禁止错误模板并进行渲染

Zend framework2 如何创建403禁止错误模板并进行渲染,zend-framework2,Zend Framework2,我想创建一个403禁止错误模板,并从控制器渲染它 在module.config.php中,我有以下条目 'view_manager' => array( 'display_not_found_reason' => true, 'display_exceptions' => true, 'doctype' => 'HTML5', 'not_found_template' =&g

我想创建一个403禁止错误模板,并从控制器渲染它

在module.config.php中,我有以下条目

    'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions'       => true,
    'doctype'                  => 'HTML5',
    'not_found_template'       => 'error/404',
    'forbidden_template'       => 'error/403',
    'exception_template'       => 'error/index',
    'template_map' => array(
        'layout/layout'           => __DIR__ . '/../view/layout/layout.phtml',
        'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
        'error/404'               => __DIR__ . '/../view/error/404.phtml',
        'error/403'               => __DIR__ . '/../view/error/403.phtml',
        'error/index'             => __DIR__ . '/../view/error/index.phtml',
    ),
    'template_path_stack' => array(
        __DIR__ . '/../view',
    ),
),
如您所见,我已将403模板和403.phtml添加到我的视图/错误文件夹中

在我的控制器中,我尝试过

$response = $this->getResponse();
$response->setStatusCode(403);
但是什么也没有发生,默认页面被呈现。当我在上面的代码中将403改为404时,404错误页面被呈现


请有人告诉我我错过了什么,非常感谢。

尝试使用onBootstrap来做这类事情(如果它适合您的应用程序)。假设您附加了一个事件以侦听事件路径:

public function onBootstrap(MvcEvent $event) {
    $eventManager = $event->getApplication()->getEventManager();
    $eventManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'protectPage'), -100);
}
现在在protectPage函数中,我们可以在任何时候决定将响应设置为禁止(403):


您需要创建一个可以注入它的侦听器
public function protectPage(MvcEvent $event) {
   $match = $event->getRouteMatch();
   ...
   $response = $event->getResponse()->setStatusCode(403);
   //If the 403 template doesnt show, you may try to redirect to an action which has the template. check the following lines.
   $match->setParam('controller', 'User\Controller\Account');
   $match->setParam('action', 'denied');
   ...
}