ZF2 return format based on accept header

LoMaX

New Member
In Zend Framework 2, I want to return JSON if the HTTP accept header is set to "application/json" and HTML otherwise. I am using the new \[code\]acceptableViewModelSelector\[/code\] controller plugin just as in the example in the 2.0.4 changelog.I have the following code:\[code\]class IndexController extends AbstractActionController { private $acceptCriteria = array( 'Zend\View\Model\JsonModel' => array('application/json'), 'Zend\View\Model\FeedModel' => array('application/rss+xml') ); public function jsonAcceptHeaderAction() { $view_model = $this->acceptableViewModelSelector($this->acceptCriteria); return $view_model; }}\[/code\]If I set the accept header like this:\[code\]curl -H "Accept: application/json" http://mydomain.com/json\[/code\]Then the controller plugin returns a \[code\]JsonModel\[/code\] instance as expected. However, it seems to always do this, even when there is no \[code\]application/json\[/code\] in my accept header. For example, if I visit the page in Chrome, the following accept headers are sent:\[code\]Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\[/code\]I also get JSON back if I use \[code\]curl http://mydomain.com/json\[/code\]. The controller plugin has a default view model name, which I expected it to use when it doesn't find a match with my accept criteria. The changelog says the following:\[quote\] The above would return a standard Zend\View\Model\ViewModel instance if the criteria is not met, and the specified view model types if the specific criteria is met.\[/quote\]I tried to change my accept criteria to the following, which turned out to do what I wanted.\[code\]private $acceptCriteria = array( 'Zend\View\Model\ViewModel' => array('text/html'), 'Zend\View\Model\JsonModel' => array('application/json'), 'Zend\View\Model\FeedModel' => array('application/rss+xml') );\[/code\]I am just wondering why it does not use the default view model name when there is no \[code\]application/json\[/code\] accept header, because ideally I would want to leave out the first entry in my accept criteria array.Does anyone know why I always get a \[code\]JsonModel\[/code\] object unless I do the change above?
 
Top