3

最近我把我的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 标头中没有 Accept 字段设置。所以我总是从服务器收到以下 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"}
 )

因此,任何人都知道如何让服务器接受来自客户端的此类请求,而标头中没有 Accept?

4

1 回答 1

3

您可以编写一个侦听器,在其中检查Accept传入请求的标头。如果没有Accept设置标题,您可以添加Accept具有默认值的标题;例如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');
}

更好的方法当然是更新您的客户。

于 2015-06-15T14:21:48.590 回答