11

我对应的配置是

fos_rest:
    view:
        view_response_listener: force

sensio_framework_extra:
    view:
        annotations: false

将路线指定为真的很烦人

@Route("/jobs", defaults={ "_format" = "json" })

每次。

那么是否可以在默认情况下在某个地方指定它?

PS:

如果我删除defaults={ "_format" = "json" }并调用/jobs端点,我会遇到异常

Unable to find template "APIBundle:Jobs:post.html.twig".

PP:

routing_loader:
    default_format: json

不起作用,因为它仅用于自动生成路线。

4

3 回答 3

22

最终的答案要容易得多,并且与 FOS\RestBundle 无关:

api:
    resource: "@APIBundle/Controller/"
    type:     annotation
    defaults: {_format: json} # <<<<<<<
    prefix:   /api/
于 2013-10-16T20:14:46.867 回答
11

如果未指定,您可以指定default_format路由加载器将用于_format参数的 a。

# app/config/config.yml
fos_rest:
    routing_loader:
        default_format: json

默认情况下,路由是使用 {_format} 字符串生成的。如果您想获得干净的 url (/jobs相反/jobs.{_format}),那么您所要做的就是添加一些配置:

# app/config/config.yml
fos_rest:
    routing_loader:
        include_format:       false

查看FOSRestBundle 文档以获取更多信息。

于 2013-10-16T07:31:23.427 回答
7

我自己无法测试此解决方案,但按照文档,您似乎可以通过在路径上给出规则来使用默认格式

config.yml

fos_rest:
    format_listener:
        rules:
            # setting fallback_format to json means that instead of considering
            # the next rule in case of a priority mismatch, json will be used
            -
                path: '^/'
                host: 'api.%domain%'
                priorities: ['json', 'xml']
                fallback_format: json
                prefer_extension: false

有了这样的,一个请求Accept-headers包含

text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json

将产生一个json请求格式

于 2013-10-16T07:49:29.503 回答