我正在通过向它发送OPTIONS命令来测试我的zf2 restful api,但它正好进入路由器中定义的操作而不是options()方法。
路由器:
'router' => array(
'routes' => array(
'edatafeed' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/api',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/:controller[/:action][/]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
控制器:
class SomeController extends ApiController
{
protected $dm;
private function getDm()
{
$this->dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
}
public function executeAction()
{
return new JsonModel(array(
'ok' => false,
'data' => null,
));
}
}
ApiController:
class ApiController extends AbstractRestfulController
{
protected function methodNotAllowed()
{
$this->response->setStatusCode(405);
throw new \Exception('Method Not Allowed');
}
public function options()
{
$response = $this->getResponse();
$headers = $response->getHeaders();
$headers->addHeaderLine('Allow', implode(',', array(
'GET',
'POST',
)))
->addHeaderLine('Content-Type','application/json; charset=utf-8');
return $response;
}
}
当我向/ api / some / execute发送OPTIONS命令时,它会直接进入执行操作,而不是进入options方法。我在路由中缺少什么?我认为发送任何OPTIONS命令会将其路由到options()。
由于
答案 0 :(得分:0)
因此,在检查请求方法类型之前,似乎AbstractRestfulController实际上检查请求是否是自定义操作。因此,我定义了一个名为" execute"它在检查它是否为OPTIONS命令之前直接路由到executeAction()。我必须覆盖我的ApiController类中的onDispatch()方法,并且只有在它的GET,POST或UPDATE命令时才会路由到我的自定义方法。否则路由到适当的方法类型方法。
这是我修改过的代码:
// RESTful methods
$method = strtolower($request->getMethod());
// Was an "action" requested?
$action = $routeMatch->getParam('action', false);
if ($action &&
($method == 'get' || $method == 'post' || $method == 'update')) {
// Handle arbitrary methods, ending in Action
$method = static::getMethodFromAction($action);
if (! method_exists($this, $method)) {
$method = 'notFoundAction';
}
$return = $this->$method();
$e->setResult($return);
return $return;
}
希望将来可以帮助其他人。
答案 1 :(得分:0)
我遇到了这个问题并按如下方式解决:
class ApiRestfullController extends AbstractRestfulController {
protected $allowedCollectionMethods = array(
'POST',
'GET'
);
public function setEventManager(EventManagerInterface $events) {
parent::setEventManager($events);
$events->attach('dispatch', function ($e) {
$this->checkOptions($e);
}, 10);
}
public function checkOptions($e) {
$response = $this->getResponse();
$request = $e->getRequest();
$method = $request->getMethod();
if (!in_array($method, $this->allowedCollectionMethods)) {
$this->methodNotAllowed();
return $response;
}
}
public function methodNotAllowed() {
$this->response->setStatusCode(
\Zend\Http\PhpEnvironment\Response::STATUS_CODE_405
);
throw new Exception('Method Not Allowed');
}
}
我希望这有助于解决问题。