【问题标题】:How does the Symfony Response Object set http headers?Symfony 响应对象是如何设置 http 头的?
【发布时间】:2014-09-20 08:07:17
【问题描述】:

我正在使用 Slex 框架。我在使用\Silex\Application::redirectmethod 时遇到了重定向问题。我发现当我尝试通过 http-headers 重定向时,响应似乎调用了 __toString 方法,而不是 symfony “发送”。

这是我的 curl 输出:

bash-4.2$ curl -v http://127.0.0.1:8082/
* About to connect() to 127.0.0.1 port 8082 (#0)
*   Trying 127.0.0.1...
* Adding handle: conn: 0x1ea0970
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x1ea0970) send_pipe: 1, recv_pipe: 0
* Connected to 127.0.0.1 (127.0.0.1) port 8082 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.32.0
> Host: 127.0.0.1:8082
> Accept: */*
> 
< HTTP/1.1 200 OK
< Date: Sat, 20 Sep 2014 08:02:52 GMT
* Server Apache/2.4.10 (Fedora) PHP/5.5.15 is not blacklisted
< Server: Apache/2.4.10 (Fedora) PHP/5.5.15
< X-Powered-By: PHP/5.5.15
< Set-Cookie: PHPSESSID=*****; path=/
< Content-Length: 116
< Content-Type: text/html; charset=UTF-8
< 
HTTP/1.0 302 Found
Cache-Control: no-cache
Date:          Sat, 20 Sep 2014 08:02:52 GMT
Location:      /login

* Connection #0 to host 127.0.0.1 left intact

我不明白为什么,但它会回显 http-headers。

更新

我的脚本是这样的:

<?php class Contorller {
    public action( \Silex\Application $app ){
       return $app->redirect('/login');
    }
}

路由脚本:

<?php
$core = new \Silex\Application;
$core->get("/another/action", "\\Controller::action")
$core->match("/login","\\AnotherController::login")->method('POST|GET');

登录动作没有逻辑,只是渲染一个树枝模板。

【问题讨论】:

  • 你的 php 脚本是什么样子的?
  • 你能添加你的路由指令和登录控制器吗?

标签: php symfony silex


【解决方案1】:

调用 $app->redirect() 返回一个新的 RedirectResponse 对象,默认状态为 302。

以下直接取自Symfony Response Object Documentation

要在 Symfony 响应对象上设置标头,请使用 headers-&gt;set 方法。

use \Symfony\Component\HttpFoundation\RedirectResponse;

class Controller {
    public function action( \Silex\Application $app ){

        $response = new RedirectResponse('/login', 302);

        // the headers public attribute is a ResponseHeaderBag
        $response->headers->set('Content-Type', 'text/plain');

        return $response;
    }
}

一旦方法名称中的拼写错误得到纠正(Contorller 更改为 Controller),您的代码就会完美运行。

class Controller {
    public function action( \Silex\Application $app ){
       return $app->redirect('/login', 302);
    }
}

class AnotherController {
    public function login( \Silex\Application $app ){
       return new Response($app['twig']->render('blank.html.twig'));
    }
}

$app->get("/another/action", "\Controller::action");
$app->match("/login","\AnotherController::login")->method('POST|GET');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-04
    • 2012-06-19
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多