![](/img/trans.png)
[英]REST service in Symfony2, with a dot in a parameter (FOSRestBundle)
[英]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_extension
為true
並調整路由定義:
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) { ... }
...
}
View
是FOS\\RestBundle\\Controller\\Annotations\\View
Route
是Symfony\\Component\\Routing\\Annotation\\Route
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.