FOS Rest Bundle-控制器必须返回Response对象,但它返回View

时间:2019-02-11 08:19:48

标签: fosuserbundle symfony4

我正在尝试在symfony 4.2.3上设置FOS Rest Bundle。并且我正在学习本教程:

https://www.thinktocode.com/2018/03/26/symfony-4-rest-api-part-1-fosrestbundle/

安装并配置了捆绑软件:

//annotations.yaml
rest_controller:
    resource: ../../src/Controller/Rest/
    type: annotation
    prefix: /api

//fos_rest.yaml
fos_rest:
  view:
    view_response_listener:  true
  format_listener:
    rules:
      - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json ] }

,当我调用我的ArticleController对象的postAction()时:

class ArticleController extends FOSRestController
{
/**
 * Creates an Article resource
 * @Rest\Post("/articles")
 * @param Request $request
 * @return View
 */
public function postArticle(Request $request): View
{
    $entityManager = $this->getDoctrine()->getManager();

    $article = new Article();

    $article->setTitle($request->get('title'));
    $article->setContent($request->get('content'));


    $articleCategory = $entityManager->getReference(ArticleCategory::class, $request->get('article_category'));
    $article->setArticleCategory($articleCategory);

    $article->setPublished($request->get('published'));

    $entityManager->persist($article);
    $entityManager->flush();

    // In case our POST was a success we need to return a 201 HTTP CREATED response
    return View::create($article, Response::HTTP_CREATED);
}

}

我收到错误消息(使用Postman进行测试): 控制器必须返回“ Symfony \ Component \ HttpFoundation \ Response”对象,但返回的对象类型为FOS \ RestBundle \ View \ View。

那是为什么?定义postArticle()方法应返回View对象,而我正在这样做。

一个通知:我的类正在扩展FOSRestController类,该类已被弃用。我还尝试扩展AbstractFOSRestController,但结果相同。

1 个答案:

答案 0 :(得分:0)

因此,由于某种原因,我的fos_rest.yaml文件不在全局的包目录中,而是在包的测试子目录中。当我将它移到它的位置时,它开始工作。