首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FOSRestBundle的多个根路由

FOSRestBundle的多个根路由
EN

Stack Overflow用户
提问于 2017-07-17 08:45:43
回答 2查看 887关注 0票数 1

我正在使用FOSRestBundle,但我找不到如何拥有两个不同的端点,一个用于模板呈现(例如html/twig,/app ),另一个用于序列化(例如json,/api )。有可能吗?FOSRestBundle Automatic Route generation的文档没有指出任何这方面的内容。

使用Symfony 3和FOSRestBundle 2.x

EN

回答 2

Stack Overflow用户

发布于 2017-07-17 21:18:44

你可以通过你的app/config.yml中的格式监听器来配置它。

代码语言:javascript
复制
fos_rest:
  format_listener:
    rules:
        - { path: '^/api', priorities: [json], fallback_format: json, prefer_extension: false }
        - { path: '^/', priorities: ['text/html', '*/*'], fallback_format: html, prefer_extension: false }
  param_fetcher_listener: force
  view:
    view_response_listener: force
    formats:
        json: true
        html: true

关于路由部分,下面是一个具有两个操作的控制器的示例,每种类型的响应(注释)对应一个操作:

代码语言:javascript
复制
namespace RVW\AppBundle\Controller;

use FOS\RestBundle\Controller\Annotations\Route;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class BrandController extends FOSRestController
{
  /**
   * @param Request $request
   * @View(statusCode=Response::HTTP_OK)
   * @Route("/brands", name="brands")
   * @Method({"GET"})
   *
   * @return View
   */
  public function brandsAction(Request $request): View
  {
    return $this->container->get('doctrine')->getRepository('AppBundle:Brand')->findAll();
  }

  /**
   * @Route("/", name="index")
   *
   * @return Response
   */
  public function indexAction(Request $request): Response
  {
    return $this->render('@App/index.html.twig', [
        'data' => $data,
    ]);
  }
}

干杯,

票数 2
EN

Stack Overflow用户

发布于 2017-09-21 13:52:38

只需在您的路由配置中指定prefix即可。

如果你正在使用YAML,你可以修改你的routing.yml文件:

代码语言:javascript
复制
app:
    resource: '@AppBundle/Controller/'
    type:      annotation
    prefix:    /app

api:
    type:     rest
    resource: AppBundle\Controller\RestController
    prefix:   /api

现在,您的普通路由以/app开头,REST路由以/api开头

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45134594

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档