我正在 Zend Framework 2 上构建 REST API。我想在发生任何错误时发送特定状态代码作为响应。
我在我的 Controller 中尝试了以下:
$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';
}
}
编辑:下面是响应的样子:
最佳答案
我刚刚在 https://github.com/akrabat/zf2-api-response-code 上用一个简单的示例项目对此进行了测试
在扩展 AbstractRestfulController
的 Controller 中,您当然可以使用
<?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 上的示例,看看它是否适用于您的服务器。
关于php - Zend 框架 2 : not able to send desired status code in response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21042369/