如何使Zf2 Apigilty接受客户端请求而不在头中设置Accept

时间:2015-06-12 01:52:33

标签: php zend-framework2 apigility content-negotiation

最近我将我的休息服务器升级到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',
        ),
    ),

问题是我的客户端(mobie app)已经部署,他们发送的帖子请求在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?

1 个答案:

答案 0 :(得分:2)

You could write a listener in which you check the Accept header of the incoming request. If no Accept header is set you can add an Accept header with a default value; for example application/json.

So something like:

/**
 * 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');
}

Better would of course be to update your client.