问题描述
我正在使用 Zend Framework 1.12 编写 REST api.我想检查控制器插件中的授权"标题.
I'm writing REST api using Zend Framework 1.12. I want to check "Authorization" header in controller plugin.
我把代码放在插件的preDispatch动作中
I put code in the preDispatch action of the plugin
$authorizationHeader = $request->getHeader('Authorization');
if(empty($authorizationHeader)) {
$this->getResponse()->setHttpResponseCode(400);
$this->getResponse()->setBody('Hello');
die(); //It doesn't work
}
问题是在它之后控制器的动作仍然被调用.我试过死()",退出".我的问题是如何从插件返回响应而不调用控制器的操作.
The problem is that after it controller's action is still being called. I tried 'die()', 'exit'. My question is how to return response from plugin and do not call controller's action.
推荐答案
几周前用这种方法用 Zend 做了一个类似的 REST API:
Did a similar REST API with Zend several weeks ago with this approach:
类变量/常量:
protected $_hasError = false;
const HEADER_APIKEY = 'Authorization';
我的预调度:
public function preDispatch()
{
$this->_apiKey = ($this->getRequest()->getHeader(self::HEADER_APIKEY) ? $this->getRequest()->getHeader(self::HEADER_APIKEY) : null);
if (empty($this->_apiKey)) {
return $this->setError(sprintf('Authentication required!'), 401);
}
[...]
}
我的自定义 setError 函数:
My custom setError Function:
private function setError($msg, $code) {
$this->getResponse()->setHttpResponseCode($code);
$this->view->error = array('code' => $code, 'message' => $msg);
$this->_hasError = true;
return false;
}
然后只需检查您的函数中是否设置了错误:
Then simply check if a error has been set inside your functions:
public function yourAction()
{
if(!$this->_hasError) {
//do stuff
}
}
如果您使用的是 contextSwitch 和 JSON,那么您的有错误的数组将被自动返回 &显示,如果发生错误:
If you're using contextSwitch and JSON, then your array with errors will be automatically returned & displayed, if an error occours:
public function init()
{
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$this->_helper->contextSwitch()->initContext('json');
[...]
}
希望能帮到你
这篇关于用于检查“授权"的 Zend Framework 1.12 插件标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!