I'm writing REST api and would like to return responses in JSON format. So, I read about about 'ContextSwitch'. But I can't make it to change headers to 'application/json' and convert data to json.
Here is code of my controller:
public function preDispatch()
{
$this->getRequest()->setParam('format', 'json');
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
public function _init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch ->addActionContext('post', 'json')
->initContext('json');
}
public function postAction()
{
echo 'test';
}
When I check response with Curl command line tool I received:
< Content-Length: 4
< Content-Type: text/html
<
* Connection #0 to host localhost left intact
test* Closing connection #0
Why header and data are not changed? How can I fix it?
Looks like the _init()
method is not executed at all. Try renaming it to init()
.