[英]Yii2 Allow action access only by POST request
我創建了一個yii2控制器,該控制器用於顯示特定用戶的數據庫統計信息。 有一個對我的控制器操作執行的ajax請求,但我想限制為該操作僅允許POST方法。
<?php
use yii\web\Response;
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\StatsModel;
class DataController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' => ['stats'],
'formats' => [
'application/json' => Response::FORMAT_JSON
],
],
];
}
/**
* {@inheritdoc}
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionStats()
{
//how can i restrict this action to only POST http method?
return StatsModel::find()->all();
}
}
我只需要將actionStats()
限制為HTTP Post方法。
通常,您只允許在您的行為中添加這樣的內容:
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'stats' => ['POST'],
],
],
如果您僅通過ajax訪問此操作,則可以在操作中添加以下檢查
if(Yii::$app->request->isAjax)
{
//in case you want to return JSON formatted response
Yii:$app->response->format = Response::FORMAT_JSON;
}
您也可以查看此食譜:
最后,您可以像這樣在操作中進行發布檢查
public function actionStats()
{
if(Yii::$app->request->isPost())
{
//your logic here
return StatsModel::find()->all();
}
else
//throw an exception or return false
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.