我有一个ASP .NET Core Web应用程序,当我创建项目时,使用单个用户帐户选项自动设置身份验证.还自动创建了用户帐户/角色的数据库表. 我创建了自己的继承自IdentityUser的ApplicationUser类,并为
我创建了自己的继承自IdentityUser的ApplicationUser类,并为FirstName,LastName和LockoutReason添加了参数. (我也将这些字段添加到数据库表中)现在我正在尝试添加一项功能,允许某人手动锁定用户,而我似乎无法更新数据库中的LockoutEnabled字段.每次我这样做,它会自动重置为false.
这是一张表格的图片:
以及它的GET / POST代码:
//GET Users lock public async Task<IActionResult> Lock(string id) { if (id == null) { return NotFound(); } var userFromDb = await _db.ApplicationUser.SingleOrDefaultAsync(m => m.Id == id); if (userFromDb == null) { return NotFound(); } else { return View(userFromDb); } } //POST Users lock [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Lock(string Id, ApplicationUser model) { var userFromDb = await _db.Users.Where(u => u.Id == Id).FirstOrDefaultAsync(); userFromDb.LockoutEnd = model.LockoutEnd; userFromDb.LockoutEnabled = true; userFromDb.AccessFailedCount = model.AccessFailedCount; userFromDb.LockoutReason = model.LockoutReason; _db.ApplicationUser.Update(userFromDb); await _db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); }
ApplicationUser.cs
public class ApplicationUser : IdentityUser { public string FirstName { get; set; } public string LastName { get; set; } public string LockoutReason { get; set; } }
单击“锁定”按钮时,LockoutEnd和LockoutReason字段会正确更新,但LockoutEnabled字段仍为false,并且帐户未被锁定.
尝试实施解决方案后的新POST方法:
//POST Users lock [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Lock(string Id, ApplicationUser model) { var userFromDb = await _db.Users.Where(u => u.Id == Id).FirstOrDefaultAsync(); userFromDb.LockoutEnd = model.LockoutEnd; userFromDb.AccessFailedCount = model.AccessFailedCount; userFromDb.LockoutReason = model.LockoutReason; _db.ApplicationUser.Update(userFromDb); await _db.SaveChangesAsync(); var user2 = await _userManager.FindByIdAsync(userFromDb.Id); var result = await _userManager.SetLockoutEnabledAsync(user2, true); return RedirectToAction(nameof(Index)); }你需要两个属性LockoutEnabled和LockoutEnd的组合.
LockoutEnabled是一个指示器,用于查看用户是否可以被锁定,并且LockoutEnd是DateTimeOffset.因此,为了锁定用户将lockout设置为true并将LockoutEnd的值放在将来,因为过去的值意味着用户未被锁定.