如何使用参数从命令行(Win 7)进行 CURL 调用到 MVC 操作?

How to make CURL call from CMD line (Win 7) to MVC action with parameter?

我正在使用 Yii 2.0 中的 CRUD 操作构建 REST-full API,我需要有关更新操作的帮助。

在我的 Yii 2.0 MVC 控制器中,我创建和更新的操作如下:

public function actionCreate()
{
    ...
}

对于创建操作,我可以使用以下命令成功调用 CURL

curl -X POST -d column_one=create_test1 -d column_two=create_test2 http://localhost/MyApp/web/tabletest/create

在此调用之后,我的 table 中的新行已成功创建,其中包含上述列值。

现在我还需要 CURL 调用更新操作:

public function actionUpdate($id)
{
    ...
}

我已经为这个命令尝试了很多变体(现在我们在函数中有参数,但我不确定如何传递它 - 让我们假设 $id=2)。这些只是我尝试过的一些,none 正在工作:

curl -X PUT -d column_two=updated_cmd_2 http://localhost/MyApp/web/tabletest/update/2

curl -X PUT -d "column_two=updated_cmd_2" "http://localhost/MyApp/web/tabletest/update/2"

curl -X PUT -d "id=2&column_two=updated_cmd_2" "http://localhost/MyApp/web/tabletest/update"

但在大多数情况下我得到了错误:

Bad Request (#400)

*注意:create方法定义为POST方法,update方法定义为PUT方法,所以这种情况下方法类型不是问题。 我认为更新的 CURL 调用格式不正确.

我通过替换控制器中的自定义操作之一解决了问题:

public function beforeAction($action) 
{
    if($this->action->id == 'create'){
        $this->enableCsrfValidation = false;
    }

    return parent::beforeAction($action);
}

进入:

public function beforeAction($action) 
{
    if($this->action->id == 'create' || $this->action->id == 'update'){
        $this->enableCsrfValidation = false;
    }

    return parent::beforeAction($action);
}

现在:

curl -X PUT -d column_two=updated_cmd_2 http://localhost/MyApp/web/tabletest/update/2

正在工作。