【问题标题】:ZF2 Restful API not routing options methodZF2 Restful API 不是路由选项方法
【发布时间】:2014-11-05 01:18:35
【问题描述】:

我正在通过向它发送一个 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()。

谢谢

【问题讨论】:

    标签: php rest zend-framework2


    【解决方案1】:

    因此,在检查请求方法类型之前,AbstractRestfulController 似乎实际上会检查请求是否针对自定义操作。因此,由于我定义了一个名为“执行”的操作,它在检查它是否是 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;
        }
    

    希望这对将来的其他人有所帮助。

    【讨论】:

      【解决方案2】:

      我遇到过这个问题,解决方法如下:

      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');
          }
      }
      

      我希望这将有助于解决问题。

      【讨论】:

        猜你喜欢
        • 2015-01-03
        • 2016-05-05
        • 1970-01-01
        • 2011-10-03
        • 2016-01-20
        • 2014-10-17
        • 1970-01-01
        • 2017-12-22
        • 1970-01-01
        相关资源
        最近更新 更多