无法使用Asp.Net标识中的UserManager.RemovePassword()和UserManager.AddP



我使用以下代码更改用户的密码:

UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = userManager.FindByName(currentUser.LoginName); // currentUser is the currently logged in user
IdentityResult result1 = userManager.RemovePassword(user.Id);
IdentityResult result2 = userManager.AddPassword(user.Id, txtPassword1.Text);

它去年有效。但今年当我运行它时,它不起作用(完全相同的代码)。当它运行到以下语句时:

IdentityResult result1 = userManager.RemovePassword(user.Id);

它给出了以下例外:

{"Cannot insert the value NULL into column 'PasswordHash', table 'xxx.dbo.AspNetUsers'; column does not allow nulls. UPDATE fails.The statement has been terminated."}

就在那句话之前,我调试到

user.PasswordHash = 'AAdcuoWRRXqfkB+vWpemPCkFNgWRGGe2tXyeJHy21S8qYYfAo9wJbfqtkog+lk2dZg=='

但在该语句之后,user.PasswordHash变为null

我真的很困惑。这里出了什么问题?

如果您想更改用户密码,请使用以下代码:

var validPass= await userManager.PasswordValidator.ValidateAsync(txtPassword1.Text);
if(validPass.Succeeded)
{
    var user = userManager.FindByName(currentUser.LoginName);
    user.PasswordHash = userManager.PasswordHasher.HashPassword(txtPassword1.Text);
    var res= userManager.Update(user);
    if(res.Succeeded)
    {
        // change password has been succeeded
    }
}

如果您想更改用户的密码,可以尝试两种方法。一种方法可以使用"RemovePassword"one_answers"AddPassword"如下:

                 string pwd = txtpwd.Text.Trim();
                var userStore = new UserStore<IdentityUser>();
                var userManager = new UserManager<IdentityUser>(userStore);
                string userName = UserName.Text;
                var user = userManager.FindByName(userName);
                if (user.PasswordHash != null)
                {
                    userManager.RemovePassword(user.Id);
                }
                userManager.AddPassword(user.Id, pwd);

另一种方法是使用"ChangePassword",如下所示:

            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
           // var user = new IdentityUser() { UserName = UserName.Text };
            if (UserName.Text != null && txtcurpwd != null && txtNewpwd != null)
            {
                string username = UserName.Text;
                var user = userManager.FindByName(username);
                IdentityResult result = userManager.ChangePassword(user.Id, txtcurpwd.Text, txtNewpwd.Text);
                if (result.Succeeded)
                    lblErrorMsg.Text = "password changed successfully for the user : " + username;
                else
                    lblErrorMsg.Text = result.Errors.FirstOrDefault();

            }
            else
                lblErrorMsg.Text = "Details missing ";
        }

相关内容

  • 没有找到相关文章

最新更新