SensioFrameworkExtraBundle

SensioFrameworkExtraBundle

我正在使用 Symfony 3.3,我正在尝试使用 FOSRestController 来制作 API.

这是我的配置文件:

# SensioFrameworkExtra Configuration
sensio_framework_extra:
    view:    { annotations: false }

# FOSRest Configuration
fos_rest:
    format_listener:
        rules:
            - { path: '^/api', priorities: ['json'], fallback_format: 'json' }
            - { path: '^/', stop: true }
    view:
        view_response_listener: true

控制器:

<?php

namespace AppBundle\Api;

use FOS\RestBundle\Controller\Annotations as REST;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;

class MyController extends FOSRestController
{

    /**
     * @REST\Get("/some-url")
     * @REST\View()
     *
     * @return View
     */
    public function getSomethingAction()
    {
        $view = View::create();

        return $view;
    }

}

问题与 view_response_listener 有关,我收到此错误消息:

(1/1) RuntimeException
You must enable the SensioFrameworkExtraBundle view annotations to use the ViewResponseListener.

路由:

api_something:
    type: rest
    resource: AppBundle\Api\MyController

捆绑包已安装并添加到 AppKernel.php 文件

有什么可以帮助我的吗?

谢谢

删除 sensio_framework_extra 的配置:

sensio_framework_extra:
    view:    { annotations: false }

因为默认配置是annotations: true(可以看vendor/sensio/framework-extra-bundle/DependencyInjection/Configuration.php)

让默认配置sensio_framework_extrahttps://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html#configuration

您可能忘记在 config.yml (https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations)

中激活序列化器的注解

我建议你试试这个配置:

#app/config/config.yml
framework:
    ....
    serializer: { enable_annotations: true }
fos_rest:
    ....
    view:
        view_response_listener: 'force'

FosRestBundle 的文档view_response_listener: http://symfony.com/doc/master/bundles/FOSRestBundle/3-listener-support.html

http://symfony.com/doc/master/bundles/FOSRestBundle/view_response_listener.html

尝试创建目录 AppBundle/Api/Controller。并将你的 MyController.php 放入其中。您的控制器将被命名为

\AppBundle\Api\Controller\MyController

复制以下代码到你的主services.yml

sensio_framework_extra.view.listener:
    alias: Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener

解法来源: https://github.com/FriendsOfSymfony/FOSRestBundle/issues/1768#issuecomment-340294485

来自 mentioned source 的另一个解决方案:

bundles.phpSensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle 必须位于 FOS\RestBundle\FOSRestBundle 之后才能正常工作

用 Symfony 4.0 回答同样的问题

routes/rest.yaml 路由配置

app_admin_users:
    type:     rest
    resource: App\Controller\Api\Admin\User\UsersController
    prefix: /api

fos_rest.yaml 查看响应侦听器已启用

fos_rest:
    view:
        view_response_listener: true

framework_extra.yaml 已启用查看注释

sensio_framework_extra:
    view:        { annotations: true }

config.yaml 导入 fos_rest 和 framework_extra

imports:
    - { resource: fos_rest.yaml }
    - { resource: framework.yaml }
    - { resource: framework_extra.yaml }