有没有办法配置我的应用程序以返回每个响应的特定标头?
我正在开发一个restful api,我需要支持跨域请求,我一直在看CORS,但我需要在每个响应中返回这样的标题:
答案 0 :(得分:0)
您可以创建自定义ResponseListener
并为每个回复设置标题:
namespace Acme\DemoBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class ResponseListener
{
public function onKernelResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
// only do something on some situations
if (false === strpos($request->headers->get('Foobar'), 'barfoo')) {
return;
}
// set the custom header of the response
$event->getResponse()->headers->set('Acme', 'demo');
}
}
然后将侦听器声明为服务:
# app/config/config.yml
services:
kernel.listener.your_listener_name:
class: Acme\DemoBundle\EventListener\ResponseListener
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
http://symfony.com/doc/current/cookbook/service_container/event_listener.html