Gee*_*eek 5 php zend-framework zend-rest zend-framework2
我正在Zend Framework 2上构建REST API.我想在发生任何错误时发送某些状态代码作为响应.
我在控制器下面尝试过:
$statusCode = 401;
$this->response->setStatusCode($statusCode);
return new JsonModel(array("error message" => "error description"));
Run Code Online (Sandbox Code Playgroud)
打印回显状态代码401,但客户端应用程序200每次都会获取状态代码.
如何将状态代码设置为特定值?
Module.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';
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:以下是响应的外观:

我刚刚在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!"));
}
}
Run Code Online (Sandbox Code Playgroud)
通过卷曲测试,我得到这个:
$ 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!"}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,响应代码集是401.如果您没有在应用程序中获得此代码,请检查我在github上的示例,看看它是否适用于您的服务器.
尝试这个:
$statusCode = 401;
$response = $this->response;
$response->setStatusCode($statusCode);
$response->setContent(new JsonModel(array("error message" => "error description")));
return $response;
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,可能会有一个onDispatch事件处理程序再次覆盖状态代码。检查你Module.php的。
| 归档时间: |
|
| 查看次数: |
3371 次 |
| 最近记录: |