asp.net - ASP.NET Core:如何使用“用户名”而不是“电子邮件”登录?
问题描述
使用 asp.net core,所有的登录页面和视图模型等都隐藏在引用的包中,因此无法直接更改。如何允许登录仍然使用用户名而不强制使用电子邮件?
解决方案
第一步是为您的应用程序构建身份:
然后您可以自定义Register.cshtml
/Register.cshtml.cs
和Login.cshtml
/ Login.cshtml.cs
,更新模型和视图,并更改函数中的逻辑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
以包含 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>
修改
Login.cshtml.cs
, 修改InputModel
为将 Email 替换为 UserName :[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
方法以使用 Username 而不是 email :var result = await _signInManager.PasswordSignInAsync(Input.UserName, Input.Password, Input.RememberMe, lockoutOnFailure: true);
默认情况下,ASP.NET Identity 用于FindByNameAsync
检查具有给定名称的用户是否存在,因此您不需要覆盖PasswordSignInAsync
. SignInManager
如果你想用电子邮件登录,你可以点击这里更新。
推荐阅读
- python-3.x - Python add ', ' to string and return:
- python-3.x - 在 python 单元测试中模拟`readlines()`
- c# - Asp.Net Core 2 - 从和到数据库的音频文件
- asp.net - Understanding App Insights end to end for occassional long response times
- android - What version number should I use for minimum in ActionCodeSettings.Builder.setAndroidPackageName()?
- mysql - Laravel relationships in CRUD application
- java - 将会话超时设置为仅在用户处于非活动状态时刷新页面并在用户处于活动状态时将其重置?
- c++ - 更新纹理的问题
- c# - NET Core 2 MVC - Storing objects for GET method
- sql - Group By 子句中的别名 - 标识符无效