如何使 Zf2 Apigilty 在 header 中没有接受设置的情况下接受客户端请求
How to make Zf2 Apigilty accept client request with no Accept set in header
最近我把rest server升级到Zf2 Apigility,内容协商设置如下,
'zf-content-negotiation' => array(
'controllers' => array(
'CloudSchoolBusFileApi\V1\Rest\FileReceiver\Controller' => 'Json',
),
'accept_whitelist' => array(
'CloudSchoolBusFileApi\V1\Rest\FileReceiver\Controller' => array(
0 => 'application/vnd.cloud-school-bus-file-api.v1+json',
1 => 'application/json',
),
),
'content_type_whitelist' => array(
'CloudSchoolBusFileApi\V1\Rest\FileReceiver\Controller' => array(
0 => 'application/vnd.cloud-school-bus-file-api.v1+json',
1 => 'application/json',
2 => 'multipart/form-data',
),
),
问题是我的客户端(手机应用程序)已经部署,他们发送 post 请求,但在 http header 中没有接受字段设置。所以我总是从服务器收到以下 406 错误,
[Response] => Array
(
[statusCode] => 406
[content] => {"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html","title":"Not Acceptable","status":406,"detail":"Cannot honor Accept type specified"}
)
所以有人知道如何让服务器在 header 中没有接受的情况下接受来自客户端的此类请求吗?
您可以编写一个侦听器,在其中检查传入请求的 Accept
header。如果没有设置 Accept
header 你可以添加一个 Accept
header 和一个默认值;例如 application/json
.
所以像这样:
/**
* Set empty accept header by default to `application/json`
*
* @param MvcEvent $event
* @return void|ApiProblemResponse
*/
public function onRoute(MvcEvent $event)
{
$request = $event->getRequest();
$headers = $request->getHeaders();
if($headers->has('Accept')){
// Accept header present, nothing to do
return;
}
$headers->addHeaderLine('Accept', 'application/json');
}
当然最好是更新您的客户端。
最近我把rest server升级到Zf2 Apigility,内容协商设置如下,
'zf-content-negotiation' => array(
'controllers' => array(
'CloudSchoolBusFileApi\V1\Rest\FileReceiver\Controller' => 'Json',
),
'accept_whitelist' => array(
'CloudSchoolBusFileApi\V1\Rest\FileReceiver\Controller' => array(
0 => 'application/vnd.cloud-school-bus-file-api.v1+json',
1 => 'application/json',
),
),
'content_type_whitelist' => array(
'CloudSchoolBusFileApi\V1\Rest\FileReceiver\Controller' => array(
0 => 'application/vnd.cloud-school-bus-file-api.v1+json',
1 => 'application/json',
2 => 'multipart/form-data',
),
),
问题是我的客户端(手机应用程序)已经部署,他们发送 post 请求,但在 http header 中没有接受字段设置。所以我总是从服务器收到以下 406 错误,
[Response] => Array
(
[statusCode] => 406
[content] => {"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html","title":"Not Acceptable","status":406,"detail":"Cannot honor Accept type specified"}
)
所以有人知道如何让服务器在 header 中没有接受的情况下接受来自客户端的此类请求吗?
您可以编写一个侦听器,在其中检查传入请求的 Accept
header。如果没有设置 Accept
header 你可以添加一个 Accept
header 和一个默认值;例如 application/json
.
所以像这样:
/**
* Set empty accept header by default to `application/json`
*
* @param MvcEvent $event
* @return void|ApiProblemResponse
*/
public function onRoute(MvcEvent $event)
{
$request = $event->getRequest();
$headers = $request->getHeaders();
if($headers->has('Accept')){
// Accept header present, nothing to do
return;
}
$headers->addHeaderLine('Accept', 'application/json');
}
当然最好是更新您的客户端。