我有一个MVC 5 Identity 2应用程序。我正在尝试更改用户密码,如下所示:
public async Task<string> ChangePassword()
{
var user = await this.UserManager.FindByIdAsync(18);
PasswordHasher hasher = new PasswordHasher();
user.PasswordHash = hasher.HashPassword("NewPassword");
this.UserManager.Update(user);
return string.Empty;
}
this.UserManager定义为:
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
该方法成功执行,但密码未更改。我错过了一步吗?
答案 0 :(得分:0)
我相信UserManager有这个方便的方法:
public virtual Task<IdentityResult> ChangePasswordAsync(
TKey userId,
string currentPassword,
string newPassword
)
修改强>
这似乎对我有用。 UserManager属性定义如下:
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
然后,密码重置方法:
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}