您好,欢迎访问一九零五行业门户网

yii2怎么进行http请求处理

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请求处理的详细内容。
其它类似信息

推荐信息