为什么我的http响应代码没有在ZF2中返回


Why is my http response code not returned in ZF2?

我正在尝试对应用程序中的用户进行身份验证。如果用户未通过身份验证,我将尝试执行以下代码

$eventManager = $e->getApplication()->getEventManager();
$eventManager->attach(MvcEvent::EVENT_ROUTE, function($e) use ($app) {
    $response = $e->getResponse();
    $response->setStatusCode(401);
    $response->setContent(json_encode(array(
           'message' => 'You are not authorised for this request',
                'name' => 'Status Forbidden'
    )));
    $app->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $e);
            return $response;
    }, PHP_INT_MAX);

为什么我无法获得上面代码中定义的http响应代码401

响应内容按预期返回。

尝试在返回响应并触发事件之前发送响应。我认为当调用触发器、响应代码和内容被替换时,这是可能的。

$response->sendResponse();