我正在编写一个ASP.NET MVC 5应用程序,该应用程序scafolded一个身份验证,但登录只使用UserName验证/登录用户。如何编辑登录方法以接受电子邮件或用户名?
答案 0 :(得分:2)
如果您对作为电子邮件地址的数据库进行制作和额外调用感到满意,请参阅以下示例。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Signin(LoginViewModel model, string returnUrl) {
if (ModelState.IsValid) {
string username = model.UserName;
ApplicationUser user = null;
// CHECK FOR EMAIL
if(IsValidEmail(username)) {
user = await userManager.FindByEmailAsync(username);
if(user != null) username = user.UserName;
else {
// If user with email address does not exists, here is a good place
// to exit as we have already ascertained that the user is not in the system
ModelState.AddModelError("", "Invalid user name or password provided.")
return View(model);
}
}
// END CHECK FOR EMAIL
user = await userManager.FindAsync(username, model.Password);
if (user != null) {
await SignInAsync(user, model.RememberMe);
.....
} else {
ModelState.AddModelError("", "Invalid user name or password provided.")
}
}
// If we got this far, something failed, re-display form
return View(model);
}
private static bool IsValidEmail(string email) {
string MatchEmailPattern =
@"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
@"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\." +
@"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|" +
@"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";
if (!IsNullOrWhiteSpace(email)) {
string pattern = MatchEmailPattern;
return System.Text.RegularExpressions.Regex.IsMatch(email, pattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
} else {
return false;
}
}
答案 1 :(得分:-1)
只需使UserName
和Email
相同即可。与在UserName字段中存储电子邮件一样。