如何在 ZF2 中将默认渲染策略更改为 JSON?

How to change default rendering strategy to JSON in ZF2?

我使用 ZF2 创建了一个 API。服务器的响应应该只包含 JSON。如果出现错误或 404 或 403 以及其他情况,它应该只是 JSON。 现在,默认情况下 ZF2 尝试 return HTML。 我用 ZendSkeletonApplication

在您的控制器中,最简单的方法是 return Zend\View\Model\JsonModel 的一个实例。例如:

$model = new JsonModel(array(
   'httpStatus' => 403,
   'title' => 'Forbidden',
   'message' => 'You are not authorized to access this page.'
));
return $model;

除非您选择 mvc 框架应用程序作为起点有特定原因,否则您可能会考虑切换到 https://apigility.org 框架。这也是一个 ZF 应用程序,但它被构建为纯粹 json api.

ZF2 在抛出异常时引发错误 by triggering specific events such as MvcEvent::EVENT_DISPATCH_ERROR or MvcEvent::EVENT_RENDER_ERROR

Zend\Mvc\View\Http\ExceptionStrategy class 附加了一些对这些事件的侦听,因此可以生成 HTML 错误页面。

对于 return JSON 错误消息,您可以附上自己的 custom exception strategy, with a higher priority, and check if the response should be JSON