Asp.Net Identity - case insensitive email and usernames

落爺英雄遲暮 提交于 2019-12-07 08:20:40

问题


Is there a way to get Asp.Net Identity to be case insensitive with email addresses and usernames?

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)


回答1:


You can change how the user is registered so that the username is set to lowercase and when logging in as well.

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);
            }
        }

And for logging in:

    [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);
    }


来源:https://stackoverflow.com/questions/24762272/asp-net-identity-case-insensitive-email-and-usernames

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!