Asp.Net身份 - 不区分大小写的电子邮件和用户名
问题描述:
有没有办法让Asp.Net身份来区分使用电子邮件地址和用户名?
Is there a way to get Asp.Net Identity to be case insensitive with email addresses and usernames?
目前,如果我称之为FindByEmailAsync(电子邮件),它只会工作,如果电子邮件地址被存储正是因为它是键入的时刻(区分大小写)
At the moment if I call "FindByEmailAsync(email)" it will only work if the email address is being stored exactly as it's is typed (case sensitive)
答
您可以更改用户是如何注册,以便用户名设置为小写,并在同时登录时。
You can change how the user is registered so that the username is set to lowercase and when logging in as well.
有关注册用户,在的AccountController
For registering the user, in the AccountController
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.Email.ToLowerInvariant(), Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
else
{
AddErrors(result);
}
}
和在日志记录:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.Email.ToLowerInvariant(), model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}