我是亚当·弗里曼的书的忠实粉丝。在他的Pro-Asp.net mvc 5平台上,在第13章第325页,以下代码让我感到困惑。有人解释过他为什么明确使用电子邮件和密码验证吗?
调用CCD_ 1应该返回具有由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);
}
}
在标识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注册,并且不关心验证电子邮件地址或密码字符串。如果要验证密码并进行自定义检查,则必须创建自定义验证器。您可以在此处找到默认UserValidator源代码