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

你说的曾经没有我的故事 提交于 2019-12-11 13:39:22

问题


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


来源:https://stackoverflow.com/questions/27921295/how-to-set-custom-headers-for-individual-controller-actions-in-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!