【问题标题】:Symfony 4 get request issueSymfony 4 获取请求问题
【发布时间】:2018-02-01 13:09:07
【问题描述】:

我试图在symfony 4 中实例化的简单服务中获取一个简单的原始json-application 请求,但它似乎与symfony 3 不同。

我的路线

deposit_money:
    path:     /auth/money/deposit
    methods: [POST]
    controller: App\Controller\MoneyController::deposit
    defaults:
        _format: json

我的控制器

public function deposit(MoneyService $moneyService)
{
    $moneyService->depositMoney();

    return new JsonResponse(
        'Money sent bla bla', JsonResponse::HTTP_NO_CONTENT
    );
}

我的服务:

class MoneyService
{
    /** @var EntityManagerInterface */
    private $entityManager;

    /** @var RequestStack */
    private $requestStack;

    /**
     * @param EntityManagerInterface $entityManager
     * @param RequestStack $requestStack
     */
    public function __construct(EntityManagerInterface $entityManager, RequestStack $requestStack)
    {
        $this->entityManager = $entityManager;
        $this->requestStack = $requestStack;
    }

    public function depositMoney()
    {
         $this->requestStack->getCurrentRequest()->setRequestFormat('json');

        var_dump($this->requestStack->getCurrentRequest()->getContent());

    }
}

我的原始请求JSON(application/json)

{
    "depositAmount":4
}

到目前为止没问题,我发送了请求并且它被完美接收但是...... 在symfony 3,当我想获取请求参数的时候,这样的就够了

$this->requestStack->getCurrentRequest()->get('depositAmount')

而在symfony 4 的这个新服务中,我首先需要以这种方式获取请求内容,以获得与 PostMan 发送的完全相同的原始 json 字符串。

$this->requestStack->getCurrentRequest()->getContent()

会跟着json转换等...

所以我的问题是... 有没有办法像

一样简单地获取参数
$this->requestStack->getCurrentRequest()->get('depositAmount')

我是否遗漏了什么,或者现在我需要将序列化注入服务并转换所有内容?

【问题讨论】:

    标签: php json symfony request symfony4


    【解决方案1】:

    看起来您的 Sf4 应用程序没有解析 json 内容。像这样的订阅者可能会对您有所帮助:JsonBodyParserSubscriber

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 2020-05-31
      • 1970-01-01
      • 2019-06-17
      • 2013-02-28
      • 2016-01-07
      • 1970-01-01
      • 2017-04-01
      相关资源
      最近更新 更多