yii2怎么进行http请求处理

(*-*)浩
(*-*)浩原创
2019-11-05 09:42:493175浏览

VerbFilter

VerbFilter 是针对 HTTP 请求方式的过滤器,作用是定义访问指定动作所允许的HTTP请求,若不允许的HTTP请求到来,则会抛出一个 HTTP 405 错误。若不指定允许的请求方式,则默认允许当所有类型的请求方式 。 (推荐学习:yii教程

接下来,试一试 VerbFilter 的简单使用。

首先,在 SiteController 中添加代码

public function actionInfo()
    {
        return \Yii::createObject([
            'class' => 'yii\web\Response',
            'format' => \yii\web\Response::FORMAT_JSON,
            'data' => [
                'message' => 'hello world',
                'code' => 100,
            ],
        ]);
    }

上述代码,返回一个利用 FORMAT_JSON 格式化的字符串

使用URL:http://localhost/basic/web/index.php?r=site/info 访问的时候,成功返回

{"message":"hello world","code":100}

接着,在 behaviors() 中添加代码

public function behaviors()
    {
        return [
            ... ...
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],                   
                    'info' => ['post'],
                ],
            ],
        ];
    }

上述代码,在 behaviors() 中使用了过滤器 VerbFilter ,指明访问动作 info 时,只能使用 POST 请求方式

此时,使用RESTClient工具,选择 GET 请求方式进行访问的时候,返回 405 错误

再次修改代码

public function behaviors()
    {
        return [
            ... ...
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],                   
                    'info' => ['post','get'],
                ],
            ],
        ];
    }

允许POST和GET两种请求方式访问动作Info,使用RESTClient工具访问,选择 GET 请求方式进行访问的时候获取到返回值

{"message":"hello world","code":100}

此时使用工具 RESTClient ,通过 post 发送请求,返回 405 错误。

这时候,修改 web.php 文件

'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => '4mWc84oNsYJpc-nnnjMwyOOiCTgcThig',
            'enableCookieValidation' => false,
            'enableCsrfValidation' => false,
        ],

添加上这两行代码,警用cookie保护与CSRF防范策略

 'enableCookieValidation' => false,
 'enableCsrfValidation' => false,

再次通过 post 发送请求访问,成功。

注:CSRF验证

因为Web网页访问的时候,form表单中会有对应的一个隐藏input:_csrf进行验证,验证通过才可以正常进行访问;

而非网页访问方式(不通过Web表单,例如用命令行CURL请求)是无法通过csrf验证的。

以上就是yii2怎么进行http请求处理的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。