来自PUT的Yii2 RESTful API post()不返回参数
我将标准的REST actionUpdate替换为只允许更新密码的版本:来自PUT的Yii2 RESTful API post()不返回参数,rest,yii2,put,Rest,Yii2,Put,我将标准的REST actionUpdate替换为只允许更新密码的版本: class UserController extends ActiveController { // ... public function actions() { $actions = parent::actions(); unset($actions['update']); return $actions; } // ...
class UserController extends ActiveController
{
// ...
public function actions()
{
$actions = parent::actions();
unset($actions['update']);
return $actions;
}
// ...
public function actionUpdate($id)
{
if (! Yii::$app->request->isPut) {
throw new MethodNotAllowedHttpException('Please use PUT');
}
/** @var User $user */
$user = User::findIdentity($id);
if (Yii::$app->request->post('password') !== null) {
$user->setPassword(Yii::$app->request->post('password'));
}
return $user->save();
}
// ...
}
[编辑]以下是用户模型:
<?php
namespace app\models\user;
use Yii;
use yii\base\NotSupportedException;
use yii\web\IdentityInterface;
class User extends \yii\db\ActiveRecord
implements IdentityInterface
{
public static function tableName()
{
return 'Users';
}
public function rules()
{
return [
[['username', 'password_hash', 'email'], 'required'],
[['role', 'status'], 'integer'],
[['username', 'email', 'last_login'], 'string', 'max' => 255],
[['username'], 'unique'],
[['email'], 'email'],
[['auth_key'], 'string', 'max' => 32],
[['password'], 'safe'],
];
}
public function beforeSave($insert)
{
$return = parent::beforeSave($insert);
if ($this->isNewRecord)
$this->auth_key = Yii::$app->security->generateRandomKey($length = 255);
return $return;
}
public function getId()
{
return $this->id;
}
public static function findIdentity($id)
{
return static::findOne($id);
}
public function getAuthKey()
{
return $this->auth_key;
}
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
public function getPassword()
{
return $this->password_hash;
}
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('You can only login by username/password pair for now.');
}
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
}
…这是正确的。当我打印
Yii::$app->request->post()
在actionUpdate中,它返回一个空数组。模型规则将“密码”列为安全的
有什么想法吗
马哈洛,
乔如果其他人感兴趣的话,这是我最终的工作方法。对于Postman,我将Json参数放在请求体中(而不是作为参数) 在Codeception中,我得到了我的线索。我不得不
$I->haveHttpHeader('Content-Type','application/json');
在$I->sendPUT(…)之前
希望这能帮助下一个人…你能发布你的用户模型吗?尝试使用补丁HTTP方法而不是PUT。在使用Codeception进行测试时,我还遇到放置请求空负载的问题。@balaji发布了用户模型。您是否将以下行更改为:if(!Yii::$app->request->isPut){throw new MethodNotAllowedHttpException('请使用PUT');}到if(!Yii::$app->request->isPatch){throw new MethodNotAllowedHttpException('请使用PUT');}actionUpdate()函数中的('Please use PATCH');}?@matej PATCH还在post()中传递一个空数组。
$I->haveHttpHeader('Content-Type','application/json');