首页 > 解决方案 > ASP.NET Core:如何使用“用户名”而不是“电子邮件”登录?

问题描述

使用 asp.net core,所有的登录页面和视图模型等都隐藏在引用的包中,因此无法直接更改。如何允许登录仍然使用用户名而不强制使用电子邮件?

标签: asp.netasp.net-core

解决方案


第一步是为您的应用程序构建身份:

ASP.NET Core 项目中的脚手架标识

然后您可以自定义Register.cshtml/Register.cshtml.csLogin.cshtml/ Login.cshtml.cs,更新模型和视图,并更改函数中的逻辑OnPostAsync以满足您的要求。

根据您的要求,您可以按照以下步骤操作:

  1. 脚手架身份融入您的项目。
  2. 修改Register.cshtml.cs,添加用户名到 InputModel

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
    
  3. 修改OnPostAsync方法:

    var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
    
  4. 更新Register.cshtml以包含 UserName :

    <div class="form-group">
        <label asp-for="Input.UserName"></label>
        <input asp-for="Input.UserName" class="form-control"/>
        <span asp-validation-for="Input.UserName" class="text-danger"></span>
    </div>
    
  5. 修改Login.cshtml.cs, 修改InputModel为将 Email 替换为 UserName :

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
    
  6. 修改Login.cshtml

    <div class="form-group">
        <label asp-for="Input.UserName"></label>
        <input asp-for="Input.UserName" class="form-control" />
        <span asp-validation-for="Input.UserName" class="text-danger"></span>
    </div>
    
  7. 修改Login.cshtml.cs OnPostAsync方法以使用 Username 而不是 email :

    var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
    

默认情况下,ASP.NET Identity 用于FindByNameAsync检查具有给定名称的用户是否存在,因此您不需要覆盖PasswordSignInAsync. SignInManager如果你想用电子邮件登录,你可以点击这里更新。


推荐阅读