gpt4 book ai didi

ASP.NET 核心 : How to login with “UserName” instead of “Email” ?

转载 作者:行者123 更新时间:2023-12-03 14:30:59 24 4
gpt4 key购买 nike

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

最佳答案

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

Scaffold Identity in ASP.NET Core projects

然后你可以自定义Register.cshtml/Register.cshtml.csLogin.cshtml/Login.cshtml.cs ,更新模型和 View ,并更改 OnPostAsync 中的逻辑功能来满足您的要求。

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

  • 将身份识别到您的项目中。
  • 修改Register.cshtml.cs , 将用户名添加到 InputModel :
    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
  • 修改OnPostAsync方法 :
    var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };
  • 更新 Register.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>
  • 修改Login.cshtml.cs , 修改 InputModel用 UserName 替换 Email :
    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
  • 修改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>
  • 修改Login.cshtml.cs OnPostAsync使用用户名而不是电子邮件的方法:
    var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);

  • 默认情况下,ASP.NET Identity 使用 FindByNameAsync检查具有给定名称的用户是否存在,以便您无需覆盖 PasswordSignInAsync函数在 SignInManager .如果您想用电子邮件登录,您可以点击 here更新那个。

    关于ASP.NET 核心 : How to login with “UserName” instead of “Email” ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55772252/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com