5

我正在 Zend Framework 2 上构建 REST API。每当发生任何错误时,我都想发送某些状态代码作为响应。

我在控制器中尝试了以下操作:

$statusCode = 401;
$this->response->setStatusCode($statusCode);
return new JsonModel(array("error message" => "error description"));

回显状态码打印401,但客户端应用程序200每次都获取状态码。

如何将状态代码设置为特定值?

模块.php:

class Module 
{
    public function getAutoloaderConfig()
    {
        return array(
                     'Zend\Loader\ClassMapAutoloader' => array(
                                                               __DIR__ . '/autoload_classmap.php',
                                                               ),
                     'Zend\Loader\StandardAutoloader' => array(
                                                               'namespaces' => array(
                                                                                     __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                                                                                     ),
                                                               ),
                     );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

}

编辑:下面是响应的样子: 在此处输入图像描述

4

2 回答 2

8

我刚刚在https://github.com/akrabat/zf2-api-response-code上用一个简单的示例项目对此进行了测试

在扩展的控制器中AbstractRestfulController,您当然可以使用

<?php
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class IndexController extends AbstractRestfulController
{
    public function create($data)
    {
        $this->response->setStatusCode(401);
        return new JsonModel(array("message" => "Please authenticate!"));
    }
}

通过 curl 测试,我得到了这个:

$ curl -v -X POST http://zf2-api-example.localhost/
* Adding handle: conn: 0x7f880b003a00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7f880b003a00) send_pipe: 1, recv_pipe: 0
* About to connect() to zf2-api-example.localhost port 80 (#0)
*   Trying 127.0.0.1...
* Connected to zf2-api-example.localhost (127.0.0.1) port 80 (#0)
> POST / HTTP/1.1
> User-Agent: curl/7.30.0
> Host: zf2-api-example.localhost
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Fri, 17 Jan 2014 10:02:47 GMT
* Server Apache is not blacklisted
< Server: Apache
< Content-Length: 34
< Content-Type: application/json; charset=utf-8
<
* Connection #0 to host zf2-api-example.localhost left intact
{"message":"Please authenticate!"}

如您所见,响应代码集为 401。如果您的应用程序没有收到此代码,请查看我在 github 上的示例,看看该代码是否适用于您的服务器。

于 2014-01-17T10:06:41.923 回答
0

尝试这个:

$statusCode = 401;
$response = $this->response;
$response->setStatusCode($statusCode);
$response->setContent(new JsonModel(array("error message" => "error description")));
return $response;

如果这不起作用,则可能有一个onDispatch事件处理程序再次覆盖状态代码。检查你Module.php的。

于 2014-01-10T12:23:51.260 回答