简体   繁体   中英

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

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM