rest - Symfony2 + FOSRestBundle : Enable/disable REST functionality per controller/action?

标签 rest symfony fosuserbundle fosrestbundle

我的应用程序的一部分将作为 提供API ,所以 我的一些页面 需要以 JSON 或 XML 格式提供(基于 Accept header “内容类型”)。

我用过 FOSRestBundle 它工作得很好,但现在 所有 发送 Accept header “内容类型:应用程序/xml”时,我的页面在 XML(或 JSON)中可用。

因此,我想为我的某些 Controller /操作启用/禁用此功能。使用注释来做到这一点是我的理想选择。

那可能吗?

我的 config.yml:

fos_rest:
    view:
        formats:
            rss: false
            xml: true 
            json: true
        templating_formats:
            html: true
        force_redirects:
            html: false
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
        view_response_listener: force
    body_listener:
        decoders:
            json: acme.decoder.json
            xml: fos_rest.decoder.xml
    format_listener:
        default_priorities: ['html', 'xml', 'json', '*/*']
        fallback_format: html
        prefer_extension: false    

最佳答案

根据 the RestBundle's documentation ,如果您不使用 View,您将不会获得 XML 输出。在您的 Controller 中。所以,如果你不使用 @View注释,或 View::create()在您的操作中,您返回一个经典响应,您将获得一个 HTML 输出。

如果因为某些原因要强制格式化,可以转prefer_extensiontrue并调整路由定义:

my_route:
    pattern:  /my-route
    defaults: { _controller: AcmeDemoBundle:action, _format: <format> }

哪里<format>是您要强制的格式。

关于rest - Symfony2 + FOSRestBundle : Enable/disable REST functionality per controller/action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11884104/

相关文章:

regex - Symfony2.0 使用正则表达式验证

symfony - FOSUser 捆绑 check_path 与本地化

php - FOSuserBundle 和 php 5.5

java - 如何在java上发送x-www-form请求?

php - 如何不使用 Doctrine 刷新 Symfony2 中的持久实体?

.htaccess - 带有 .htaccess 的 HTTPS 和 REST API

php - FatalErrorException : Error: Call to a member function getId() on a non-object in . ..PostListener.php 第 20 行

symfony - FOSUserBundle 覆盖注册表格

rest - 如何使用 REST API 获取身份验证 token 或登录 Elastic Search?例如来自 postman

http - REST 问题 : PUT one representation, 换一个?