I want to change the default headers collection in my RESTful api. I can change the header with set() method on every response that I send, but i don't want to write
$response = Yii::$app->response;
$response->headers->set('X-Powered-By','My server <devel>')
$response->setStatusCode(somecode);
$response->data = somedata;
return $response;
This is quite cumbersome and my Controller actions grow at length, as i have to respond to every bad request and error. I have tried to change the response component in rest/config/main.php, but I am forbidden to change headers property, as it is read-only.
Please help.
You don't need to go to the trouble of extending the response class. You can do this by configuring the response
component of the application and adding custom headers in the beforeSend
event, e.g.:
return [
...
'components' => [
...
'response' => [
'on beforeSend' => function($event) {
$event->sender->headers->add('X-Frame-Options', 'DENY');
},
],
...
],
];
This will add the header(s) for all responses. If you want to do it per controller, you can use \Yii::$app->response->headers->add($name, $value);
in the afterAction()
method of the controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With