可以在SF3中注册控制器操作以使用特定的“内容类型”吗?
我试图放弃'/ api / post / {id} / xml'路线黑客。
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class BlogApiController extends Controller
{
/**
* @Route("/api/posts/{id}")
* @Method({"GET","HEAD"})
* some-magic-annotation-here
*/
public function showJson($id)
{
// response in json
}
/**
* @Route("/api/posts/{id}")
* @Method({"GET","HEAD"})
* some-magic-annotation-here
*/
public function showXml($id)
{
// response in XML
}
}
答案 0 :(得分:1)
使用_format
:
class BlogApiController extends Controller
{
/**
* @Route("/api/posts/{id}.{_format}", defaults={"_format": "json"})
* @Method({"GET","HEAD"})
*/
public function getPost($id, $_format)
{
// Retrieve your object
if ('xml' == $_format) {
return $this->showXml($object);
}
return $this->showJson($object);
}
}
如果您需要检查传入请求的内容类型:
$contentType = $request->headers->get('Content-Type');
if (0 === strpos($contentType, 'application/json')) {
return $this->showJson($object);
} elseif (0 === strpos($contentType, 'application/xml')) {
return $this->showXml($object);
}
下次,如果您尚未使用它,则应使用Serializer组件,并删除两个show[format]
方法,例如:
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$responseBody = $serializer->serialize($object, $_format);
答案 1 :(得分:1)
根据official documentation,您可以使用 condition 参数:
/**
* @Route(
* "/api/posts/{id}",
* condition="request.headers.get('Content-Type') === 'application/json'"
* )
* @Method({"GET","HEAD"})
*/
public function showJson($id)
{
...
与XML相同。
在条件下,您必须使用expression syntax