[英]Use Username instead of Email for identity in Asp.net mvc5
每当我使用Visual Studio 2013 Express为Web创建新应用程序并使用个人帐户身份验证并单击注册按钮时,我就会注意到它实现了“电子邮件”而不是“用户名”,并且在LoginViewModel中也是如此,因为它使用电子邮件来登录而不是用户名。 我如何才能将其更改为使用用户名而不是默认电子邮件,而不会遇到麻烦? 我也想知道如何将字符串类型的默认“ guid”转换为“ id”(整数类型)。
接受的答案中的链接问题描述了如何使用电子邮件代替用户名,OP希望使用用户名代替电子邮件,这是我在MVC项目的Identity 2.0中所寻找的。
万一其他人从谷歌搜索到达这里,实际上很容易做到这一点。 如果您查看注册后操作,只需将UserName设置为Email地址。 所以.........
将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>
在AccountController上的Register Post Action中,将UserName设置为ViewModel的UserName,将Email设置为ViewModel的Email。
var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
为了使电子邮件不唯一:
在IdentityConfig中进行以下配置
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
请调查这个线程
线程详细信息:
假设:
删除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; }
}
由于用户可以输入Username
或Email
,因此我们将使用@字符作为验证条件。 这是要实现的流程:
Email
验证,否则应用Username
格式验证。 Email
,首先我们需要获取Username
。 由于认为Username
是唯一的,因此我们可以使用userManager.FindByEmailAsync
方法获取它。 使用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);
无需特别更改View。 运行该应用程序并使用电子邮件或用户名测试登录名。
注意 :请记住,本教程遵循MVC .Net Identity默认结构。
您也可以这样使用用户名和/或密码
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.