How to set custom headers for individual controlle

2019-08-04 22:40发布

问题:

I want to never the response of some of my controller actions in zend framework 2.

This is the definitions of one my said controllers:

'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',
        ),
    ),
),

I want none of the responses that this controller supplies to be cached. I tried setHeader like this:

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

inside the action functions, and it doesn't work. I also set the correct headers on the layout .pthml

回答1:

You're on the right way. You just need the actual Zend\Http\Headers instance via $this->getResponse()->getHeaders() inside the related action.

Try this:

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