在我的 MVC(5.1) 应用程序中。我想添加密码更改。
这就是我所做的,
public class AccountController : Controller
{
private readonly ILicenserepository _licenserepository;
private readonly IUserRepository _userRepository;
public AccountController(ILicenserepository licenserepository, IUserRepository userRepository)
{
_licenserepository = licenserepository;
_userRepository = userRepository;
//UserManager = userManager;
}
public UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new DatePickerDbContext()));
....
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Manage(ManageUserViewModel model)
{
bool hasPassword = HasPassword();
ViewBag.HasLocalPassword = hasPassword;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasPassword)
{
if (ModelState.IsValid)
{
string userId = User.Identity.GetUserId();
IdentityResult result = UserManager.ChangePassword(userId, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
else
{
// User does not have a password so remove any validation errors caused by a missing OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
else
{
AddErrors(result);
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
当我运行应用程序时,我在浏览器上收到此错误
Invalid length for a Base-64 char array or string.
在行
IdentityResult result = UserManager.ChangePassword(userId, model.OldPassword, model.NewPassword);
我不知道怎么了。是因为我还没有在构造函数中初始化我的UserManger
吗?
当我检查 userId, model.OldPassword and model.NewPassword
中的值时,所有值都符合我的预期。 userId 保存 userId 值,oldpassword 保存 oldpassowrd 值,新密码保存用户提供的新密码值。
这是我
愚蠢的错误我之前曾创建过这样的用户
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.Lastname,
Phone = model.Phone,
Email = model.EmailId,
Company = model.Company,
PasswordHash = model.ConfirmPassword
UserName = model.UserName,
DateTimeRegistered = DateTime.UtcNow,
License = model.SelectedLicense,
IsApproved = true,
};
var result = UserManager.Create(user);
在这里,密码不会被散列并保存为用户提供的确切字符串。
这造成了错误。
创建用户时应该提供密码,例如
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.Lastname,
Phone = model.Phone,
Email = model.EmailId,
Company = model.Company,
UserName = model.UserName,
DateTimeRegistered = DateTime.UtcNow,
License = model.SelectedLicense,
IsApproved = true,
};
var result = UserManager.Create(user,model.ConfirmPassword);