如何在API Platform自定义处理器中获取请求格式?
解决方案
要在自定义QrCodeProcessor中获取请求并执行格式检查等逻辑,无需依赖序列化或自定义控制器,只需通过依赖注入引入RequestStack即可实现。
修改后的处理器代码
use Symfony\Component\HttpFoundation\RequestStack; use ApiPlatform\Metadata\Operation; use ApiPlatform\Processor\ProcessorInterface; use Symfony\Component\HttpFoundation\Response; class QrCodeProcessor implements ProcessorInterface { public function __construct(private readonly RequestStack $requestStack) {} public function process( mixed $data, Operation $operation, array $uriVariables = [], array $context = [] ) { // 获取当前请求实例 $request = $this->requestStack->getCurrentRequest(); // 检查请求格式,例如验证Content-Type $contentType = $request->getContentTypeFormat(); if ($contentType !== 'json') { // 返回自定义格式错误响应 return new Response('请求格式无效,请使用JSON格式', Response::HTTP_BAD_REQUEST); } // 读取请求原始内容(按需使用) $requestContent = $request->getContent(); // 执行自定义业务逻辑 $content = '处理完成的二维码内容'; return new Response($content); } }
关联处理器到POST操作
通过API Platform配置将处理器绑定到POST /api/qr-codes操作,以注解方式为例:
use ApiPlatform\Metadata\Post; #[Post( uriTemplate: '/api/qr-codes', processor: QrCodeProcessor::class )] class QrCode { // 实体定义(按需编写) }
这样就能在不依赖序列化和自定义控制器的前提下,完成请求格式检查与自定义逻辑执行。
内容的提问来源于stack exchange,提问作者gremo
相关产品推荐
相关产品推荐

