How to Return custom HTTP status code in Zend Framework 2

zend-framework2

Solution

Your controller already has a Response object, set the status code on that and just return

    if (!$this->isApiKeyValid()) {
        $this->getResponse()->setStatusCode(401);
        return;
    }

Problem

I am trying to return a 401 http status-code if a given apikey is not correct: ``` class MessageRestfulController extends AbstractRestfulController { # ... public function get($id) { if (!$this->isApiKeyValid()) { $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_401); return $response; } # ... return new JsonModel(array( 'data' => array(...) )); } } ``` For my controller i have added `'strategies' => array('ViewJsonStrategy)'` because it is a AbstractRestfulController and should return json if operation was successful. I am really new to ZF2 and dont know what the correct way is to implement such an exception. The way i am currently doing it, does not work. Thanks for your hints!

Original source