如何在 ZF2 中为各个控制器操作设置自定义标头


How to set custom headers for individual controller actions in ZF2?

我不想在 zend Framework 2 中响应我的一些控制器操作。

这是我所说的一个控制器的定义:

'login' => array(
    'type' => 'segment',
    'options' => array(
        'route'    => '/login[/:action][/:id]',
        'constraints' => array(
            'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
            'id' => '[a-zA-Z0-9]*',
        ),
        'defaults' => array(
            'controller' => 'Presentation'Controller'Login',
            'action'     => 'index',
        ),
    ),
),

我不希望缓存此控制器提供的任何响应。我尝试了这样的setHeader:

$this->getResponse()
    ->setHeader('Cache-Control', 'no-cache, no-store, must-revalidate', true)
    ->setHeader('Pragma', 'no-cache', true)
    ->setHeader('Expires', '0', true);

在操作功能中,它不起作用。我还在布局 .pthml 上设置了正确的标题

你走对了路。你只需要通过相关操作中的$this->getResponse()->getHeaders()实际的 Zend''Http''Headers 实例。

试试这个:

public function myAction()
{
    $headers = array(
        'Cache-Control' => 'no-cache, no-store, must-revalidate',
        'Pragma'        => 'no-cache',
        'Expires'       => false,
        );
    $this->getResponse()->getHeaders()->addHeaders($headers);
}