【问题标题】:How to set custom headers for individual controller actions in ZF2?如何为 ZF2 中的各个控制器操作设置自定义标头?
【发布时间】:2015-01-13 11:38:37
【问题描述】:

我不想在 zend 框架 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

【问题讨论】:

    标签: php zend-framework2


    【解决方案1】:

    你是在正确的方式。您只需要通过相关操作中的$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);
    }
    

    【讨论】:

    • 是的,这确实有效,并且标题已正确添加。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2014-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多