【发布时间】:2021-09-27 00:19:57
【问题描述】:
我将通过 Http Put 操作更新我的哈希密码。
这是我的模型:
[Key, DatabaseGenerated (DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FullName { get; set; }
public string UserName { get; set; }
[NotMapped]
public string Password { get; set; }
[Required]
public byte[] PasswordHash { get; set; }
[Required]
public byte[] PasswordSalt { get; set; }
public byte UserRole { get; set; }
这是我的控制器:
[HttpPut("{Id}")]
public async Task<IActionResult> PutUser([FromRoute] int Id, [FromBody] TheUser user)
{
if (Id != user.Id)
{
return BadRequest();
}
CreatePasswordHash(user.Password, out byte[] passwordHash, out byte[] passwordSalt);
_context.Entry(user).State = EntityState.Modified;
user.PasswordHash = passwordHash;
user.PasswordSalt = passwordSalt;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (_context.TheUser.Find(Id) == null)
{
return NotFound();
}
throw;
}
catch
{
return BadRequest();
}
return NoContent();
}
private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
当我运行应用程序时,我收到以下错误:
其实我是要在不知道之前密码的情况下重设用户密码。
但问题是两个变量 passwordHash 和 passwordSalt 没有得到值。
【问题讨论】:
-
您实际得到的错误仅与模型验证有关。您已将 PasswordHash 和 PasswordSalt 标记为 [必需]。删除它。您不会将这些字段从视图中发布回来。相反,您在后端填充它们。
标签: c# asp.net-core-webapi asp.net-core-3.1