我正在开发基于Symfony 4.1.0的微服务,它在config / routes.yaml中定义了以下REST API:
import:
path: /sip/calls/
controller: App\Controller\ApiController::import
methods: [POST]
问题是对/sip/calls
的POST请求导致NotFoundHttpException
(找不到“POST / sip / calls”的路由)。如果我从config / routes.yaml中的路径路径中删除尾部斜杠,则/sip/calls
的请求将通过,但/sip/calls/
将停止工作。
为什么表现如意?如何使它忽略斜线或缺席?
答案 0 :(得分:1)
如下所述:Redirecting URLs with Trailing Slashes Symfony 4.1通过创建重定向301来处理此内容。但问题是此重定向不适用于POST请求。
正如这里提到的Why doesn't HTTP have POST redirect理论上你可以使用重定向307或308,但过去我遇到了一些问题,所以我选择带有重复路径和斜杠的简单解决方案。
答案 1 :(得分:1)
这是@LukaszJakubek指出的预期行为。如果你需要两种方式匹配路线,你可以分配多条路线,它应该工作:
#config/routes.yaml
with_slash:
path: test/
controller: App\Controller\TestController::something
methods: [POST]
without_slash:
path: test
controller: App\Controller\TestController::something
methods: [POST]
使用debug命令时的结果:
bin/console router:match /test --method=POST
[OK] Route "without_slash" matches
+--------------+---------------------------------------------------------+
| Property | Value |
+--------------+---------------------------------------------------------+
| Route Name | without_slash |
| Path | /test |
| Path Regex | #^/test$#sD |
| Host | ANY |
| Host Regex | |
| Scheme | ANY |
| Method | POST |
| Requirements | NO CUSTOM |
| Class | Symfony\Component\Routing\Route |
| Defaults | _controller: App\Controller\TestController::something |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
+--------------+---------------------------------------------------------+
bin/console router:match /test/ --method=POST
[OK] Route "with_slash" matches
+--------------+---------------------------------------------------------+
| Property | Value |
+--------------+---------------------------------------------------------+
| Route Name | with_slash |
| Path | /test/ |
| Path Regex | #^/test/$#sD |
| Host | ANY |
| Host Regex | |
| Scheme | ANY |
| Method | POST |
| Requirements | NO CUSTOM |
| Class | Symfony\Component\Routing\Route |
| Defaults | _controller: App\Controller\TestController::something |
| Options | compiler_class: Symfony\Component\Routing\RouteCompiler |
+--------------+---------------------------------------------------------+