当请求中未指定 Accept-Type 时,如何使 Apigility 不 return 406

How do I get Apigility to not return 406 when no Accept-Type is specified in the request

我有一个 Titanium Android 应用程序可以显示来自 URL 的图像。我想使用 apigilty 来提供这些图像。

我有一个流响应 RPC 服务,它在从浏览器调用时工作。但是在 android 上它不起作用,因为看起来 android ImageView 没有发送 Accept-Type header 并且 Apigiilty 拒绝了带有 [=14= 的呼叫].

有没有一种方法可以配置我的 apigility 项目以忽略仅针对此 RPC 服务的 Accept-Type 检查?

传入请求的 Accept header 在 ZF\ContentNegotiationAcceptFilterListener class and if no accept header is present the validateMediaType method returns false and then the ApiProblemResponse is created at line 55 中检查。

当然,最好的办法是确保在所有请求中都接受一个 accept header,但如果这是不可能的,您可以在所有请求中设置一个默认的 accept header请求。

你可以简单地通过在你的应用程序中添加这个Module.php方法来解决它:

/**
 * {@inheritDoc}
 */
public function onBootstrap(MvcEvent $event)
{
    $application    = $event>getApplication();
    $eventManager   = $application->getEventManager();

    // Attach setDefaultAcceptHeader method with higher priority then AcceptFilterListener
    $eventManager->attach(MvcEvent::EVENT_ROUTE, [$this, 'setDefaultAcceptHeader'], 100);
}

/**
 * @var MvcEvent $event
 */
public function setDefaultAcceptHeader(MvcEvent $event)
{
    $request = $event->getRequest();

    if( ! $request instanceof \Zend\Http\Request){
        // Not a http request, return
        return;
    }
    // Check if we have an accept header, if not set to 'application/json'
    $headers = $request->getHeaders();
    if(!$headers->has('accept')){
        $headers->addHeaderLine('accept', 'application/json');
    }
}