yii2 RESTful API 405 Method Not Allowed

关于 Yii2 中 RESTful API 的开发,可以参考另一篇随笔 http://www.cnblogs.com/ganiks/p/yii2-restful-api-dev.html

测试的过程中遇到一个这样的问题, 报错 405 yii2 RESTful API 405 Method Not Allowed

比如请求 PUT 方法 的 http://192.168.4.126/news/162?access-token=100-token

{
    "type": "yii\web\MethodNotAllowedHttpException",
    "name": "Method Not Allowed",
    "message": "Method Not Allowed. This url can only handle the following request methods: GET, HEAD.",
    "code": 0,
    "status": 405
}

这里由于不是在 yii2 的前台框架体系中,因此没有看到堆栈的调试信息,但是要调试也要找到这个报错 message 的所在:

yii2filtersVerbFilter.php

    public function beforeAction($event)
    {
        $action = $event->action->id;  
        if (isset($this->actions[$action])) {
            $verbs = $this->actions[$action];
        } elseif (isset($this->actions['*'])) {
            $verbs = $this->actions['*'];
        } else {
            return $event->isValid;
        }

        $verb = Yii::$app->getRequest()->getMethod();
        $allowed = array_map('strtoupper', $verbs);
        if (!in_array($verb, $allowed)) {
            $event->isValid = false;
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7
            Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed));
            throw new MethodNotAllowedHttpException('Method Not Allowed. This url can only handle the following request methods: ' . implode(', ', $allowed) . '.');
        }

        return $event->isValid;
    }

这里调试打印一下 $action , 发现每次无论传入什么 $event->action->id 都是 view

因此我断定问题出在 URL, yii 没有正确辨识出 http://192.168.4.126/news/163

去看看 config 中的 URLManager Rules, 这里当时多余的把 老式的 url rules 放在这里,去掉试试

			'rules' => [
				#'<controller:w+>/<id:d+>' => '<controller>/view',
				#'<controller:w+>/<action:w+>/<id:d+>' => '<controller>/<action>',
				#'<controller:w+>/<action:w+>' => '<controller>/<action>',
				['class' => 'yii
estUrlRule', 'controller' => ['users', 'news']],
			],

果然, 解决了问题

作者:ganiks
出处:http://www.cnblogs.com/ganiks/
本作品由 Ganiks 创作, 欢迎转载,但任何转载必须保留完整文章,在显要地方显示署名以及原文链接。如您有任何疑问,请给我留言。
原文地址:https://www.cnblogs.com/ganiks/p/yii2-RESTful-API-405-Method-Not-Allowed.html