ZF2 return format based on accept header

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 controller plugin acceptableViewModelSelector , as in the example in change list 2.0.4 .

I have the following 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; } } 

If I set the accept header as follows:

curl -H "Accept: application/json" http://mydomain.com/json

The controller plugin then returns an instance of JsonModel as expected. However, this seems to always happen, even if there is no application/json in my accept header. For example, if I visit a page in Chrome, the following receiving headers are sent:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

I also get JSON if I use curl http://mydomain.com/json . The controller plugin has a default view model name, which I expected to be used when it does not match my acceptance criteria. The change log indicates the following:

The above will return a standard instance of Zend \ View \ Model \ ViewModel if the criteria are not met, and the specified types of the view model if specific criteria are met.

I tried changing the accept criteria to the following, which turned out to do what I wanted.

 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') ); 

I'm just wondering why it doesn't use the default view model name when there is no application/json accept header, because ideally I would like to leave the first entry in my array of acceptance criteria.

Does anyone know why I always get a JsonModel object if I don't do it above?

+4
source share
1 answer

The default presentation model works, there is no problem with your code, if you do not have a text / html entry, if you access the URL with any browser that can accept json, the acceptance criteria will correspond to the first entry, i.e. application / json.

To test the default model, your url is checked with curl, as shown below, without writing text / html in an array of an acceptable model, you will get the default view model output

 curl -H "Accept: text/html" http://mydomain.com/json 

This will return the default view model, so to work, since you expect that you need a text / html entry, put the entry in an array with your preferred order

0
source

All Articles