How to force Zf2 Apigilty to accept client request without Accept set in header
I recently upgraded my rest server to Zf2 Apigility whose settings are as follows:
'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',
),
),
The problem is my client (mobile app) is already deployed and is sending mail requests without setting the "Accept" field in the http header. so i always got 406 error from server,
[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"}
)
So, does anyone know how to allow the server to accept such a request from a client without an Accept in header?
source to share
You can write a listener where you check the header of the Accept
incoming request. If there is no title Accept
, you can add a title Accept
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');
}
It would be better, of course, to update your client.
source to share