문제

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