Shopware 6如何添加自定义Admin API路由与控制器?报412错误如何解决?
问题原因
Shopware 6 对路由有严格的作用域校验规则,Admin API 对应的路由必须明确标注api作用域,你当前的自定义路由没有声明对应作用域,触发了路由校验规则,所以返回412错误。
解决步骤
步骤1:修改控制器的路由注解,添加作用域声明
把控制器里的@Route注解补充defaults参数,标注路由属于api作用域,修改后的控制器代码如下:<?php declare(strict_types=1); namespace GIW\LiqPay\Controller\Api; use Shopware\Core\Framework\Context; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\JsonResponse; class ExampleApiController extends AbstractController { /** * @Route("/api/example", name="api.action.boilerplate.example-api-action", methods={"GET"}, defaults={"_routeScope"={"api"}}) */ public function exampleApi(Request $request, Context $context): JsonResponse { return new JsonResponse(['You successfully created your first controller route']); } }步骤2:调整路由配置文件存放位置
不要把Admin API的路由导入配置放在普通的routes.xml中,应该在插件的src/Resources/config/目录下新建api_routes.xml,把原来的路由导入配置挪到这个文件里,Shopware会自动识别该文件配置的路由为API路由,无需额外全局注册,配置内容如下:<?xml version="1.0" encoding="UTF-8" ?> <routes xmlns="http://symfony.com/schema/routing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/routing https://symfony.com/schema/routing/routing-1.0.xsd"> <import resource="@GIWLiqPay/Controller/Api/ExampleApiController.php" type="annotation" /> </routes>步骤3:(可选)优化服务配置
你当前的services.xml配置可以正常工作,也可以补充控制器标签减少冗余配置,修改后的services.xml配置如下:<service id="GIW\LiqPay\Controller\Api\ExampleApiController" public="true"> <tag name="controller.service_arguments"/> </service>步骤4:清理缓存使配置生效
执行Shopware缓存清理命令:bin/console cache:clear,清理完成后路由即可正常访问。
验证
重新发起GET请求到/api/example,即可正常收到返回内容:
["You successfully created your first controller route"]
内容的提问来源于stack exchange,提问作者Mikael
相关产品推荐
相关产品推荐

