Router::extensions(['json']) 对 ErrorController 没有影响

Router::extensions(['json']) has no effect on the ErrorController

我的目标是在请求时将异常消息转换为 JSON(通过 headers and/or 文件扩展名)。根据 ,这需要在 src/Controller/ErrorController.php 中发生。如果我只是将 $this->RequestHandler->renderAs($this, 'json') 添加到 beforeFilter() 它工作正常,但话又说回来,我应该仅在明确请求 JSON 时才强制使用 JSON。

当我请求它时,我可以看到扩展名根本没有被解析:

object(Cake\Http\ServerRequest) {
    [protected] params => [
        'controller' => 'Foo',
        'action' => 'bar.json',
        // …
        '_ext' => null,
    ]

尝试 $this->getRequest()->is('json') 也 returns false

当我将 debug(Router::extensions());exit; 添加到 config/routes.php 的顶部时,没有任何反应。这是否意味着根本没有读取文件?还是因为异常在它到达那里之前就中止了执行?

如何在明确请求时强制显示 JSON 错误消息?

相关代码:

  1. 在相应范围内使用 setExtensions() 而不是全局调用
  2. 如果使用前缀,请配置准确的前缀
  3. 清除缓存:bin/cake cache clear_all

如果操作正确,将不需要额外配置src/Controller/ErrorController.php

工作代码:

Router::prefix('myprefix', function ($routes) {
    $routes->setExtensions(['json']);
    $routes->fallbacks(DashedRoute::class);
});

就是这样。请求在 /myprefix 内具有 .json 扩展名的请求将返回为 JSON.