繁体   English   中英

Symfony2 + FOSRestBundle:为每个控制器/操作启用/禁用REST功能?

[英]Symfony2 + FOSRestBundle: Enable/disable REST functionality per controller/action?

我的应用程序的一部分将作为API提供 ,因此我的一些页面需要以JSON或XML(基于Accept标头'Content Type')提供。

我已经使用了FOSRestBundle ,它运行得很好,但现在发送Accept标头'Content Type:application / xml'时,我的所有页面都以XML(或JSON)形式提供。

所以,我想为我的一些控制器/操作启用/禁用此功能。 使用注释我会很理想。

那可能吗?

我的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    

根据RestBundle的文档 ,如果您不在控制器中使用View ,则不会获得XML输出。 因此,如果您未在操作中使用@View注释或View::create() ,并且返回经典响应,则将获得HTML输出。

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

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

其中<format>是您要强制使用的格式。

您可以将view_response_listener设置为false (默认为force )。 然后将@View注释添加到您要使用REST的每个控制器类中。

示例将使其更清晰。

没有REST的控制器:

/**
 * @Route("/comments")
 */
class CommentsControler extends Controller
{
    /**
     * @Route("/")
     * @Method({"POST"})
     */
    public function newAction() { ... }

    /**
     * @Route("/{id}")
     */
    public function detailAction($id) { ... }

    ...
}

还有另一个REST控制器。 请注意,只需要@View注释(除非您要覆盖响应状态代码)。

/**
 * @View
 * @Route("/api/comments")
 */
class RestfulCommentsControler extends Controller
{
    /**
     * @Route("/")
     * @Method({"POST"})
     */
    public function newAction() { ... }

    /**
     * @Route("/{id}")
     */
    public function detailAction($id) { ... }

    /**
     * @View(statusCode=204)
     * @Route("/{id}/delete")
     */
    public function deleteAction($id) { ... }

    ...
}
  • ViewFOS\\RestBundle\\Controller\\Annotations\\View
  • RouteSymfony\\Component\\Routing\\Annotation\\Route

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM