【问题标题】:Symfony redirect response errorSymfony 重定向响应错误
【发布时间】:2018-04-12 12:18:58
【问题描述】:

尝试重定向到另一个方法时出现此错误

类型错误:参数 1 传递给 Symfony\Component\HttpFoundation\ResponseHeaderBag::__construct() 必须 是数组类型,给定整数,调用 /proyect/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Response.php 在第 199 行

但我发送的是一个空数组

return new RedirectResponse('persons', array(), UrlGeneratorInterface::RELATIVE_PATH);

有什么帮助吗?

【问题讨论】:

  • 如果您在控制器中,那么您可能想要使用 return $this->redirectToRoute('persons');否则, RedirectResponse::__construct(?string $url, int $status = 302, array $headers = array())
  • 这是一个很好的答案,但如果需要相对路径怎么办?
  • 然后你传给它一个相对的url。班级不在乎。再一次,如果您在控制器中,请使用 $this->generateUrl() ,它为您提供绝对或相对选项。

标签: php symfony redirect


【解决方案1】:

这是HttpFoundation\RedirectResponse 类吗?你的实例化看起来不对。

// Symfony\Component\HttpFoundation\RedirectResponse

public function __construct($url, $status = 302, $headers = array())
{
    ...
}

你的第三个参数是一个整数,当需要一个数组时。 RedirectResponse 构造函数调用其父构造函数 Response 构造函数,并执行以下代码:

// Symfony\Component\HttpFoundation\Response

public function __construct($content = '', $status = 200, $headers = array())
{
    $this->headers = new ResponseHeaderBag($headers);
    ...
}

这是您的错误,当预期值为响应标头数组时,您使用的是整数(UrlGeneratorInterface::RELATIVE_PATH,等于 2)。

@Cerad 回答正确的解决方案是使用 redirectToRoute 方法,但它会将您重定向到绝对路径:

return $this->redirectToRoute('persons', array());

或者,如果您仍想将 RedirectResponse 与相对路径一起使用:

$url = $this->generateUrl('persons', array(), UrlGeneratorInterface::RELATIVE_PATH);

return new RedirectResponse($url);

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 2018-02-19
    • 2017-07-12
    • 1970-01-01
    • 2015-04-24
    • 2016-10-20
    • 2016-06-20
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多