Symfony 3.4 / routing:参数值中的Urlencoded“/”导致与路由不匹配

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Symfony 3.4 / routing:参数值中的Urlencoded“/”导致与路由不匹配相关的知识,希望对你有一定的参考价值。

所以,我会解释这个问题,实际的问题是,如果它是一个Bug:

$routes = new RouteCollection();
$context = new RequestContext('/');
$matcher = new UrlMatcher($routes, $context);

$route = new Route('/foo/{name}');
$routes->add('route_name', $route);
$parameters = $matcher->match('/foo/somedata%2Fblax');

这给出了一个例外'找不到“/ foo / somedata%2Fblax”的路线

如果从路径中删除%2F(url编码的斜杠),如:

$parameters = $matcher->match('/foo/somedatablax');

然后一切正常,$参数:

array (size=2)
  'name' => string 'somedatablax' (length=12)
  '_route' => string 'route_name' (length=10)

所以进一步将url模式设置为/foo/somedata/{name}

 $routes = new RouteCollection();
 $context = new RequestContext('/');
 $matcher = new UrlMatcher($routes, $context);

 $route = new Route('/foo/somedata/{name}');   
 $routes->add('route_name', $route);
 $parameters = $matcher->match('/foo/somedata%2Fblax');

这将返回:

array (size=2)
  'name' => string 'blax' (length=4)
  '_route' => string 'route_name' (length=10)

这意味着当匹配模式时,url编码的斜杠被视为常规斜杠,这似乎是错误的(这不是url编码存在的原因之一吗?)

我做了一些调查,发现为什么这种方式有效(虽然不容易修复)

这是一个错误还是我的逻辑中有任何流程?它显然看起来像一个bug,但它似乎已经存在了很长一段时间(从一开始可能是?)

还有一种解决方案(实际上不是,它并不意味着解决这个特殊问题,但仍然相关):symfony4symfony2相同。

答案

默认情况下,任何路由参数都匹配字符“/”,尽管您可以使用参数要求设置正则表达式以匹配您认为合适的值。

https://symfony.com/doc/current/routing/requirements.html

$routes = new RouteCollection();
$context = new RequestContext('/');
$matcher = new UrlMatcher($routes, $context);

$route = new Route('/foo/{name}', [], ['name'=>'.+']);
$routes->add('route_name', $route);
$parameters = $matcher->match('/foo/somedata%2Fblax');

现在它应该匹配你的路线。

虽然你是对的。 symfony路由器在匹配路由之前执行rawurldedecode:

供应商/ symfony的/ symfony的/ SRC / Symfony的/组件/路由/匹配器/ UrlMatcher.php

    /**
     * {@inheritdoc}
     */
    public function match($pathinfo)
    {
        $this->allow = array();

        if ($ret = $this->matchCollection(rawurldecode($pathinfo), $this->routes)) {
            return $ret;
        }
        [...]
    }

以上是关于Symfony 3.4 / routing:参数值中的Urlencoded“/”导致与路由不匹配的主要内容,如果未能解决你的问题,请参考以下文章

如何将令牌存储作为参数传递给 Symfony 3.4 中的事件监听器

Symfony 3.4 - 将 API 流文件传输到客户端下载

Symfony2 / 路由 / 使用参数作为控制器或动作名称

Symfony 强制参数缺失

Symfony 更新 2.8 到 3.4

Hwi oauth bundle 和 Symfony 3.4 无法自动装配服务:如何在 symfony 3.4 + FOSUserBundle 中使用 hwi/oauth-bundle