将用户登录从“电子邮件”更改为“用户名”
本文关键字:电子邮件 用户 用户名 登录 | 更新日期: 2023-09-27 18:22:44
在ASP.NET MVC 5中,默认情况下,登录和注册设置附带电子邮件和密码。我想改为使用用户名和密码。这里有很多类似的案例,但关注它们并没有帮助。当我尝试注册时,我收到一条错误消息,上面写着"电子邮件不能为空"。似乎电子邮件的设置在某个地方仍然有效,不确定在哪里。我对用户用户名而不是电子邮件所做的更改如下:
AccountViewModel
//Removed Email and added username for RegisterViewModel
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
public string Username { get; set; }
}
账户管理员在注册时将电子邮件更改为用户名
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{ //changed email to username
var user = new ApplicationUser { UserName = model.Username};
//var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
Register.cshtml
<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" })
</div>
</div>
我会做同样的登录后,了解我错过了什么步骤。
这是一个猜测,所以请耐心等待。
在启动时,您可以配置AddIdentity。
像这样的东西很可能存在:
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
将其更改为
// Add Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(options => {
options.User.RequireUniqueEmail = false; })
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
这是基于使用EF和https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNet.Identity/UserValidator.cs#L55