如何指定FOS\RestBundle到json的默认格式?

zer*_*kms 11 php symfony fosrestbundle symfony-2.3

我的相应配置是

fos_rest:
    view:
        view_response_listener: force

sensio_framework_extra:
    view:
        annotations: false
Run Code Online (Sandbox Code Playgroud)

将路线指定为,真的很烦人

@Route("/jobs", defaults={ "_format" = "json" })
Run Code Online (Sandbox Code Playgroud)

每次.

那么可以在默认情况下将其指定在某个地方吗?

PS:

如果我删除defaults={ "_format" = "json" }并调用/jobs端点我得到一个例外

Unable to find template "APIBundle:Jobs:post.html.twig".
Run Code Online (Sandbox Code Playgroud)

PPS:

routing_loader:
    default_format: json
Run Code Online (Sandbox Code Playgroud)

将无法工作,因为它仅用于自动路线生成.

zer*_*kms 21

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

api:
    resource: "@APIBundle/Controller/"
    type:     annotation
    defaults: {_format: json} # <<<<<<<
    prefix:   /api/
Run Code Online (Sandbox Code Playgroud)


Pic*_*oss 10

如果没有指定default_format,您可以指定路由加载器将用于_format参数的路径.

# app/config/config.yml
fos_rest:
    routing_loader:
        default_format: json
Run Code Online (Sandbox Code Playgroud)

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

# app/config/config.yml
fos_rest:
    routing_loader:
        include_format:       false
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看FOSRestBundle文档.


Tou*_*uki 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
Run Code Online (Sandbox Code Playgroud)

有这样的,用Accept-headers包含的请求

text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
Run Code Online (Sandbox Code Playgroud)

将导致json请求格式