【问题标题】:How to redirect without GET parameters using the routing?如何使用路由在没有 GET 参数的情况下重定向?
【发布时间】:2013-04-03 13:21:55
【问题描述】:

我的路由是这样定义的:

# New URLs
article_show:
    pattern:  /article/{id}
    defaults: { _controller: AcmeDemoBundle:Article:show }

# Old URLs
article_show_legacy:
    path:            /article-{id}-{param}.html
    requirements:
        param: foo|bar
    defaults:
        _controller: FrameworkBundle:Redirect:redirect
        route:       article_show
        permanent:   true

我想知道如何在没有param 参数的情况下将article_show_legacy 重定向到article_show。目前,每当我访问/article-1-foo.html(例如)时,我都会被重定向到/article/1?param=foo。我想丢弃?param=foo,所以我被重定向到/article/1

我知道我可以为foo 创建一条路线,为bar 创建一条路线,但就我而言,还有更多情况。

我必须编写自己的重定向控制器吗?

【问题讨论】:

  • 我通常在我的控制器或树枝中处理这个业务逻辑,你想要一个仅配置类型的解决方案还是我应该发布那种类型的响应?
  • 我知道我可以在控制器中处理它,但我想知道路由组件是否提供了自动处理它的东西。

标签: php redirect symfony routing symfony-2.2


【解决方案1】:

您必须编写自己的重定向控制器或在任何现有控制器中创建重定向方法。

查看../vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.phpRedirectControllerredirect 操作以获取更多详细信息。

一些例子(我添加了第三个选项stripAttributes):

public function redirectAction($route, $permanent = false, $stripAttributes = false)
{
    if ('' == $route) {
        return new Response(null, $permanent ? 410 : 404);
    }

    $attributes = array();
    if (!$stripAttributes) {
        $attributes = $this->container->get('request')->attributes->get('_route_params');
        unset($attributes['route'], 
              $attributes['permanent'], 
              $attributes['stripAttributes']);
    }

    return new RedirectResponse($this->container->get('router')->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $permanent ? 301 : 302);
}

【讨论】:

  • 太棒了!我只是做了类似的事情,并使用了array 作为第三个参数。
猜你喜欢
  • 2017-06-01
  • 2019-10-15
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
相关资源
最近更新 更多