How to login with “UserName” instead of “Email” in MVC Identity?

大兔子大兔子 提交于 2019-12-18 12:14:21

问题


I need to set my login to use username instead of email address, how can I change it?


回答1:


It's actually using the e-mail address as the username, so in the ASPNetUsers table, you'll see both the username and email fields with the email address.

Go into the AccountController, look for Register method (POST).

Change this:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email};

to this:

var user = new ApplicationUser
            {
                UserName = model.UserName,
                Email = model.Email
            };

Then go into the Login.cshtml and change all corresponding e-mail model fields to username instead.

Finally, go into the Login method (POST) in the AccountController and change model.Email to model.UserName.

var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, 
             model.RememberMe, shouldLockout: false);

You also have to make changes in AccountViewModels.cs in order to introduce your new UserName property.




回答2:


Here is how you do it

 var user = await _userManager.Users
           .FirstOrDefaultAsync(u => u.UserName == username || u.Email == username); 
 if (user != null){
    var result = await _signInManager
                .PasswordSignInAsync(/*email*/user.Email, password, false, false);
    /*removed for brevity*/
 }

Think you have a user having username=test and email=myemail@example.com then you would like to allow users to authenticate using test instead of myemail@... `

PS. While the answer from @Jason works, sometimes you'd like to authenticate a user with real username and password, not using the email.

In this case use my answer



来源:https://stackoverflow.com/questions/33069201/how-to-login-with-username-instead-of-email-in-mvc-identity

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