简体   繁体   English

在Asp.net mvc5中使用用户名代替电子邮件作为身份

[英]Use Username instead of Email for identity in Asp.net mvc5

Whenever I create a new application with visual studio 2013 express for web and using the individual accounts authentication and i hit the register button I notice that it implements 'Email' instead of 'Username' and the same is in the LoginViewModel as it uses Email to Sign in instead of Username. 每当我使用Visual Studio 2013 Express为Web创建新应用程序并使用个人帐户身份验证并单击注册按钮时,我就会注意到它实现了“电子邮件”而不是“用户名”,并且在LoginViewModel中也是如此,因为它使用电子邮件来登录而不是用户名。 How can i change this to use Username instead of the default Email without trouble? 我如何才能将其更改为使用用户名而不是默认电子邮件,而不会遇到麻烦? Also i would like to know how to convert the default 'guid' that is a string type to 'id' (integer type). 我也想知道如何将字符串类型的默认“ guid”转换为“ id”(整数类型)。

The linked question in the accepted answer descibes how to use Email instead of UserName, OP wanted the UserName instead of email which is what I was looking for in Identity 2.0 in an MVC project. 接受的答案中的链接问题描述了如何使用电子邮件代替用户名,OP希望使用用户名代替电子邮件,这是我在MVC项目的Identity 2.0中所寻找的。

In case anyone else gets here from a google search it is actually very easy to do this. 万一其他人从谷歌搜索到达这里,实际上很容易做到这一点。 If you look at the register post action it is simply setting the UserName to the Email address. 如果您查看注册后操作,只需将UserName设置为Email地址。 So......... 所以.........

Add UserName to the RegisterViewModel and add it to the register view. 将UserName添加到RegisterViewModel并将其添加到注册视图。

<div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control", @placeholder = "Username or email" })
        </div>
</div>

In the Register Post Action on the AccountController set the UserName to the ViewModel's UserName and the Email to the ViewModel's Email. 在AccountController上的Register Post Action中,将UserName设置为ViewModel的UserName,将Email设置为ViewModel的Email。

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

In order to make email as non unique: 为了使电子邮件不唯一:

Configure below in IdentityConfig 在IdentityConfig中进行以下配置

manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = false                
            };

Please look into this thread 请调查这个线程

Thread Details : 线程详细信息:

Assumptions: 假设:

  1. Username is unique for each user. 用户名对于每个用户都是唯一的。 It is either input by user or generated by application on registration. 它可以由用户输入,也可以由应用程序在注册时生成。
  2. No @ symbol allowed in Username. 用户名中不允许使用@符号。

Remove EmailAddress annotation and define Display text in the default LoginViewModel : 删除EmailAddress批注,并在默认的LoginViewModel定义Display文本:

public class LoginViewModel
{
    [Required]
    [Display(Name = "Username/Email")]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

As user can enter either Username or Email , so we will make @ character for validation criteria. 由于用户可以输入UsernameEmail ,因此我们将使用@字符作为验证条件。 Here is the flow to be implemented: 这是要实现的流程:

  1. If in the string @ is present, apply Email validation else apply Username format validation. 如果字符串@中存在,则应用Email验证,否则应用Username格式验证。
  2. In case of valid Email , first we need to get Username . 如果使用有效的Email ,首先我们需要获取Username As it is considered that Username is unique so we can get it with userManager.FindByEmailAsync method. 由于认为Username是唯一的,因此我们可以使用userManager.FindByEmailAsync方法获取它。
  3. Use Username for SignIn verification. 使用Username进行SignIn验证。

     public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (model.Email.IndexOf('@') > -1) { //Validate email format string emailRegex = @"^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}" + @"\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; Regex re = new Regex(emailRegex); if (!re.IsMatch(model.Email)) { ModelState.AddModelError("Email", "Email is not valid"); } } else { //validate Username format string emailRegex = @"^[a-zA-Z0-9]*$"; Regex re = new Regex(emailRegex); if (!re.IsMatch(model.Email)) { ModelState.AddModelError("Email", "Username is not valid"); } } if (ModelState.IsValid) { var userName = model.Email; if (userName.IndexOf('@') > -1) { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } else { userName = user.UserName; } } var result = await _signInManager.PasswordSignInAsync(userName, model.Password, model.RememberMe, lockoutOnFailure: false); 

No special need to change in View. 无需特别更改View。 Run the application and test login with Email or Username. 运行该应用程序并使用电子邮件或用户名测试登录名。

Note : Keep in mind this tutorial follows MVC .Net Identity default structure. 注意 :请记住,本教程遵循MVC .Net Identity默认结构。

You can also use username and/or password like this 您也可以这样使用用户名和/或密码

var user = await _userManager.Users
       .FirstOrDefaultAsync(u => u.UserName == username || u.Email == username);

if (user != null){
var result = await _signInManager
            .PasswordSignInAsync(user.Email, password, false, false);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM