How to set custom headers for individual controlle

2019-08-04 22:25发布

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条回答
Bombasti
2楼-- · 2019-08-04 22:42

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);
}
查看更多
登录 后发表回答