我是Adam Freeman的书的粉丝。在他的Pro Asp.net mvc 5平台上,在第13章,第325页,以下代码使我感到困惑。有没有人解释为什么他明确地使用了电子邮件和密码验证?
致电this.UserManager.UpdateAsync(user)
应返回this.UserManager.UserValidator.ValidateAsync(user)
和this.UserManager.PasswordValidator.ValidateAsync(password)
生成的相同错误的结果。他两次不做同样的事吗?还是有特殊目的?
[HttpPost]
public async Task<ActionResult> Edit(string id, string email, string password)
{
AppUser user = await this.UserManager.FindByIdAsync(id);
if (user != null)
{
user.Email = email;
IdentityResult validEmail = await this.UserManager.UserValidator.ValidateAsync(user);
if (!validEmail.Succeeded)
{
this.AddErrorsFromResult(validEmail);
}
IdentityResult validPass = null;
if (password != string.Empty)
{
validPass = await this.UserManager.PasswordValidator.ValidateAsync(password);
if (validPass.Succeeded)
{
user.PasswordHash = this.UserManager.PasswordHasher.HashPassword(password);
}
else
{
this.AddErrorsFromResult(validPass);
}
}
if ((validEmail.Succeeded && validPass == null)
|| (validEmail.Succeeded && password != string.Empty && validPass.Succeeded))
{
IdentityResult result = await this.UserManager.UpdateAsync(user);
if (result.Succeeded)
{
return this.RedirectToAction("Index");
}
this.AddErrorsFromResult(result);
}
}
else
{
ModelState.AddModelError(string.Empty, "User not found");
}
return this.View(user);
}
private AppUserManager UserManager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
}
}
private void AddErrorsFromResult(IdentityResult result)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError(string.Empty, error);
}
}
答案 0 :(得分:1)
在身份的源代码中UserManager类的UpdateAsync方法是这样的:
public virtual async Task<IdentityResult> UpdateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var result = await UserValidator.ValidateAsync(user).ConfigureAwait(false);
if (!result.Succeeded)
{
return result;
}
await Store.UpdateAsync(user).ConfigureAwait(false);
return IdentityResult.Success;
}
调用UserValidator.ValidateAsync(user)
方法验证该用户名是非法的,或者用户之前未使用其他所有者ID注册,并且不关心验证电子邮件地址或密码字符串。如果要验证密码并进行自定义检查,则必须创建自定义验证器。
你可以找到Default UserValidator source code here