更新 AspNet Core 身份的字段

Update Fields of AspNet Core Identity

我正在尝试使用 ASP.NET CORE WEB API 使用 UpdateAsync 方法更新 AspNetUser 的某些字段。我尝试了以下但抛出错误显示用户名不能为空。对于这种情况,我只想更新电话号码。

控制器

    public async Task<IActionResult> UpdateUserAync([FromBody] RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var result = await _userService.UpdateUserAsync(model);
            if (result.IsSuccess)
                return Ok(result);
            return BadRequest(result);


        }
        return BadRequest("Some Properties are not valid!");

    }

服务

  public async Task<UserUpdateResponse>  UpdateUserAsync(RegisterViewModel model)
    {
        var user = await _userManager.FindByEmailAsync(model.Email);
        var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
        if (user == null)

            throw new NullReferenceException("Update model is null");

        if (phoneNumber!=null)
            return new UserUpdateResponse
            {
                Message = "Sorry you can't update!",
                IsSuccess = false,
            };

        var identityUser = new IdentityUser
        {

            PhoneNumber = model.PhoneNumber


    };
        var result = await _userManager.UpdateAsync(identityUser);

        if (result.Succeeded)
        {
            return new UserUpdateResponse
            {
                Message = "Phone number updated Successfully",
                IsSuccess = true,
                Errors = result.Errors.Select(e => e.Description)
            };

        }
        return new UserUpdateResponse
        {
            Message = "Phone number didnot Updated!",
            IsSuccess = false,
            Errors = result.Errors.Select(e => e.Description)
        };

    }

在这里,我只想根据用户 email/user id 更新某些字段。

错误信息

{
"message": "Phone number didnot Updated!",
"isSuccess": false,
"errors": [
    "User name '' is invalid, can only contain letters or digits."
],
"expireDate": null

}

Entity Framework 尝试 INSERT 这个用户,而不是 UPDATE 它,因为你创建了 IdentityUser:

的新实例
var identityUser = new IdentityUser
{
    PhoneNumber = model.PhoneNumber
}

这就是您遇到错误的原因。对于 UPDATE 用户,您需要通过 FindByEmailAsync 方法找到的更新 user

// Get the existing user from the db
var user = await _userManager.FindByEmailAsync(model.Email);

// Update it with the values from the view model
user.Name = model.Name;
user.Surname = model.Surname;
user.UserName = model.UserName;
user.Email = model.Email;
user.PhoneNumber = model.PhoneNumber;
user.PasswordHash = checkUser.PasswordHash;

// Apply the changes
var result = await _userManager.UpdateAsync(user);