更新用户信息2种情况-有密码和无密码



我有一个管理面板,希望有两个选项作为管理员更新用户信息。一种情况是我只想更新用户角色,另一种情况则是我想更新所有信息,包括用户忘记密码时的密码。

RegisterModel.cs:

public class RegisterModel
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserRoles { get; set; }
public byte[] ProfilePicture { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
//[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
//[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

AuthorizeController.cs

public async Task<IActionResult> UpdateUser([FromBody] RegisterModel model)
{
ApplicationUser existingUser = await this.UserManager.FindByIdAsync(model.Id);
if (!string.IsNullOrEmpty(model.Email))
{
IList<string> existingRoles = await this.UserManager.GetRolesAsync(existingUser);
IdentityResult output = await this.UserManager.RemoveFromRoleAsync(existingUser, existingRoles.FirstOrDefault());
IdentityResult resultat = await this.UserManager.AddToRoleAsync(existingUser, model.UserRoles);
Collection<ApplicationUserRole> userRoles = new();
userRoles.Add(new ApplicationUserRole { Name = model.UserRoles });
existingUser.Email = model.Email;
existingUser.FirstName = model.FirstName;
existingUser.LastName = model.LastName;
existingUser.ProfilePicture = model.ProfilePicture;
existingUser.UserRoles = userRoles;
if (!string.IsNullOrEmpty(model.Password))
{
existingUser.PasswordHash = this.PasswordHasher.HashPassword(existingUser, model.Password);
existingUser.PasswordHash = this.PasswordHasher.HashPassword(existingUser, model.ConfirmPassword);
}
IdentityResult result = await this.UserManager.UpdateAsync(existingUser);
if (!result.Succeeded)
{
var errors = result.Errors.Select(x => x.Description);
return BadRequest(new RegisterResult { Successful = false, Errors = errors });
}
return Ok(new RegisterResult { Successful = true });
}
return NotFound("User not found!");
}

目前,我无法将RegisterModel.cs密码字段设置为"必需",因为在这种情况下,我不能将它们留空。然而,我使用相同的模型来创建新用户,在这种情况下,他们是必需的。此外,当前代码在DB中进行了必要的更改,但我在上遇到了一个异常

IdentityResult result = await this.UserManager.UpdateAsync(existingUser);

Microsoft.AspNetCore.Components.WebAssembly.Frendering.WebAssemblyRenderer[100]未处理的异常呈现组件:"S"是无效的值开头。路径:$|LineNumber:0|BytePositionInLine:0。System.Text.Json.JsonException:"S"是无效的值开头。路径:$|LineNumber:0|BytePositionInLine:0--->System.Text.Json.JsonReaderException:"S"是无效的价值行号:0|BytePositionInLine:0。在System.Text.Json.SthrowHelper.ThrowJsonReaderException(Utf8JsonReadR&json,ExceptionResource资源,Byte nextByte,只读span1 bytes) at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker) at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first) at System.Text.Json.Utf8JsonReader.ReadSingleSegment() at System.Text.Json.Utf8JsonReader.Read() at System.Text.Json.Serialization.JsonConverter1[[Blazing.Shared.RegisterResult,Blazing.Shared,版本=1.0.0.0,文化=中性,PublicKeyToken=null]].ReadCore(Utf8JsonReader&reader,JsonSerializerOptions选项,ReadStack&state(---内部结束异常堆栈跟踪--在System.Text.Json.SthrowHelper.ReThrowWithPath(ReadStack&state,JsonReaderException ex(System.Text.Json.Serialization.JsonConverter1[[Blazing.Shared.RegisterResult, Blazing.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[RegisterResult](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state) at System.Text.Json.JsonSerializer.ReadCore[RegisterResult](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan1缓冲区,JsonSerializerOptions选项,ReadStack&状态,JsonConverterconverterBase(System.Text.Json.JsonSerializer.ContinueDeserialize[RegisterResult](ReadBufferState&bufferState,JsonReaderState&jsonReaderState,ReadStack&readStack,JsonConverter转换器,JsonSerializerOptions选项(System.Text.Json.JsonSerializer.d__651[[Blazing.Shared.RegisterResult, Blazing.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext() at System.Net.Http.Json.HttpContentJsonExtensions.<ReadFromJsonAsyncCore>d__41[[Blazing.Shared.RegisterResult,Blazing.Shared,版本=1.0.0.0,文化=中性,PublicKeyToken=null]].MoveNext((

根据您的描述,您有一个new user creation pageadmin update user page,它们使用相同的用户模型,在创建新用户时,密码是必要的,而在更新用户时则不需要。所以有两种方式摆在你面前。

正在为更新页面创建新的用户模型。你知道这很容易,但我认为当你选择在这里提问时,你的目标并不是这个。所以我认为你必须在这里添加更多的商业逻辑。

例如,您可以将password属性更改为not required,并要求您的创建/更新按钮的单击事件检查此操作是否需要输入密码,并且在后端代码中,您还可以添加关于此传入请求是否为"的判断代码;需要密码";在不符合规则时请求并返回错误,以避免有人直接调用后端控制器。这种方式将需要检查的密码留给您自己的代码。

另一种方法是保持密码仍然是必需的,但现在您需要为";不需要密码";脚本当您的后端收到一个";不需要密码";请求时,它应该首先从数据库中查询出密码,并在模型验证之前将密码添加到数据模型中,这样它也可以使密码";所需";。

[HttpPost]
public IActionResult Edit([Bind("name,age,password")] UserModel user)
{
//password is required here 
//if without the line-code below and the password is null here, it will return "password is required"
user.password = "cccc";
//Data validation
if (ModelState.IsValid)
{

return RedirectToAction(nameof(Index));
}
return View(user);
}

根据你的错误消息,我发现一个博客分享了类似的问题,所以我认为你需要检查UserManager.UpdateAsync返回了什么数据,以及它是否是IdentityResult

相关内容

  • 没有找到相关文章

最新更新