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().

其他提示

As i think your code has missing some steps to call context switch helper

here is working example for me to use context switch for rest api

just go throw this API example and make your script to work

hope this will sure help you.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top