当前位置:网站首页>Quickly master asp Net authentication framework identity - user registration
Quickly master asp Net authentication framework identity - user registration
2022-06-22 17:04:00 【Dotnet cross platform】
Recommended attention 「 Code Xia Jianghu 」 Add Star standard , Never forget the Jianghu Affairs
This is a ASP.NET Core Identity The second article in the series , The last article introduced Identity Integration of framework , And some basic knowledge .
This article talks about how to ASP.NET Core Identity User registration in .
Click on the blue word above or behind , read ASP.NET Core Identity Collection of series .
The sample project for this article :https://github.com/zilor-net/IdentitySample/tree/main/Sample02

preparation
ASP.NET Core Identity There are many different identity options , Help us achieve user registration .
First , Let us in 「Models」 In the folder , Create a user registration model :
public class UserRegistrationModel
{
[Display(Name = " surname ")]
public string FirstName { get; set; }
[Display(Name = " name ")]
public string LastName { get; set; }
[Display(Name = " email ")]
[Required(ErrorMessage = " Email cannot be empty ")]
[EmailAddress]
public string Email { get; set; }
[Display(Name = " password ")]
[Required(ErrorMessage = " The password cannot be empty ")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = " Confirm the password ")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = " The password does not match the confirmation password .")]
public string ConfirmPassword { get; set; }
}Properties in this class , Users are required to fill in the registration form .
among ,Email and Password Properties are required ,ConfirmPassword The value of the property must be the same as Password The value of the property matches .
With this model , Let's create another 「Account」 controller :
public class AccountController : Controller
{
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Register(UserRegistrationModel userModel)
{
return View();
}
} It has two Register Operation method , Used to provide user registration function .
first Register Method acceptance Get request , View used to display the registration form ;
the second Register Method acceptance Post request , Used to handle user registration logic , And display a view of the registration results .
Also need to GET Register operation , Create a view , Here we can use Create Templates , Model class selection UserRegistrationModel The class can .

Now the form in this view , It is already possible to register models for users , All input fields are provided .
It should be noted that , We'd better modify the form asp-validation-summary The value of is All.
because , By default , It can only display error messages generated by model validation , It will not display the validation errors we set ourselves .
In the view Create Button , Will jump to POST Requested Register Operation method , And populate the user registration model .
stay Web API Using data from users in , It is better to use the method of data transmission object , But in MVC This is not necessarily the case in .
This is because MVC There are models , With views , The model to some extent , It replaces the responsibility of data transmission objects .
Because our data is passed through views , So this kind of model is also called view model .
「UserRegistrationModel」 Is a view model , If we want to really store it in the database , It must be mapped to User Entity class .
We need to install AutoMapper :
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection then , stay Program Class :
builder.Services.AddAutoMapper(Assembly.GetExecutingAssembly());next , On the navigation menu of the layout page , Add a registration button .
Because the login button will be added later , So for code maintainability , We can create a partial view :
// Shared\_LoginPartial.cshtml
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link text-dark" asp-controller="Account"
asp-action="Register"> register </a>
</li>
</ul>Last , modify 「_Layout.cshtml」 Layout view , Add login distribution view on the navigation menu :
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
<partial name="_LoginPartial" /><!-- add to -->
<ul class="navbar-nav flex-grow-1">Register operation
The preparatory work has been completed .
Now? , Let's start with the user registration logic .
First , Must be in 「Account」 The controller , Inject AutoMapper and UserManager class :
private readonly IMapper _mapper;
private readonly UserManager<User> _userManager;
public AccountController(IMapper mapper, UserManager<User> userManager)
{
_mapper = mapper;
_userManager = userManager;
}「UserManager」 from Identity Framework provide , It is responsible for helping us manage users in our applications .
The user registration logic is in Post Requested Register Method implementation :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(UserRegistrationModel userModel)
{
if(!ModelState.IsValid)
{
return View(userModel);
}
var user = _mapper.Map<User>(userModel);
var result = await _userManager.CreateAsync(user, userModel.Password);
if(!result.Succeeded)
{
foreach (var error in result.Errors)
{
ModelState.TryAddModelError(error.Code, error.Description);
}
return View(userModel);
}
await _userManager.AddToRoleAsync(user, "Guest");
return RedirectToAction(nameof(HomeController.Index), "Home");
}What needs to be noted here is , We changed this method to asynchronous , because ·UserManager· The helper method of is also asynchronous .
Inside the method , First check the validity of the model , If it is invalid , Return the same view with invalid model .
If the inspection passes , will userModel Shoot to user Entity .
Use CreateAsync Method to register users , It hashes the password and saves it .
after , Check the creation result it returns .
If created successfully , We just need to UserManager With the help of the , Use AddToRoleAsync Method , Add a default role to the user , And redirect the user to Index page .
But if the registration fails , Just go through all the errors , And add them to ModelState in .
Previously, we have changed the validation information summary of the view to All, Otherwise, the error added here , It doesn't show up .
Last , Don't forget to create AutoMapper Mapping configuration class for :
// MappingProfile.cs
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<UserRegistrationModel, User>()
.ForMember(
user => user.UserName,
expression => expression.MapFrom(userModel => userModel.Email));
}
}Here we map email to user name , Because we do not provide the field of user name in the registration form .
Now start the application , Test the user registration .
I can try all kinds of wrong registration content , Observe the verification results .
It should be noted that , Default password verification rules , Very complicated , It requires not only upper and lower case letters , You must also have a special symbol .
This password rule is very good , But sometimes I may not need strong rules .
And we used email as the username , But by default , There is no requirement that email is the only .
therefore , We can change these rules , This needs to be registered Identity The place of , Modify through configuration options :
services.AddIdentity<User, IdentityRole>(options =>
{
options.Password.RequiredLength = 6;
options.Password.RequireDigit = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireLowercase = false;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationContext>();such as , We have eliminated the numbers here 、 Verification of capital letters and special characters , The minimum length is changed to 6 position , At the same time, set the unique verification of e-mail .
Now let's start the application , Test the registration process , For example, the wrong password format 、 Duplicate email .
Through some tests, we can find , Some error messages are in Chinese 、 Some are in English .
Because there are two types of errors , One is our custom model validation error , We have set the error message , So this type is Chinese .
The other is ASP.NET Core Identity Built in validation error , It is through the operation method , Read and add to the model state by yourself .
because ASP.NET Core Identity It's in English , So what we get is information in English ,
however , We can also define Chinese information by ourselves , This requires us to create a custom error description class :
public class CustomIdentityErrorDescriber : IdentityErrorDescriber
{
public override IdentityError PasswordTooShort(int length)
{
return new()
{
Code = nameof(PasswordTooShort),
Description = $" The password needs at least {length} position "
};
}
public override IdentityError DuplicateEmail(string email)
{
return new()
{
Code = nameof(DuplicateUserName),
Description = $" email {email} Already exists ."
};
}
public override IdentityError DuplicateUserName(string username)
{
return new()
{
Code = nameof(DuplicateUserName),
Description = $" user name {username} Already exists ."
};
}Custom error messages , Need to override 「IdentityErrorDescriber」 Wrong method of base class , Set the error description you want .
If necessary , You can read the source code , Find all the wrong methods .
We also need to configure it to register Identity In the service approach :
AddErrorDescriber<CustomIdentityErrorDescriber>()Summary
Now? , We have implemented user registration , See the example project for the specific code , The next article will continue to explain user login and identity authentication .
More highlights , Please pay attention to me. ▼▼

If you like my article , that
Watching and forwarding is my greatest support !
( Stamp the blue words below to read )ASP.NET 6 The most easy to understand dependency injection series
Check and fill gaps, and learn from the system EF Core 6 series

Recommends WeChat official account : Code Xia Jianghu
I think it's good , Point and watch before you go
边栏推荐
- What are the characteristics of the interactive whiteboard? Function introduction of electronic whiteboard
- Qt笔记-QMap自定义键(key)
- Hello Playwright:(7)模拟键盘和鼠标
- spark-shuffle的读数据源码分析
- WPF效果第一百九十篇之再耍ListBox
- C#-Linq源码解析之DefaultIfEmpty
- STM32通过DMA进行ADC采集(HAL库)
- [C language] use of library function qsort
- Bidirectional data binding V-model and v-decorator
- Docker 之MySQL 重启,提示Error response from daemon: driver failed programming external connectivity on **
猜你喜欢
![Web technology sharing | [Gaode map] to realize customized track playback](/img/0b/25fc8967f5cc2cea626e0b3f2b7594.png)
Web technology sharing | [Gaode map] to realize customized track playback

Qt筆記-QMap自定義鍵(key)

Social responsibility: GAC Honda advocates children's road traffic safety in "dream children's travel"

jsp學習之(二)---------jsp脚本元素和指令

写给 Kubernetes 工程师的 mTLS 指南
![[pop up box 2 at the bottom of wechat applet package]](/img/31/266e6a1f4200347c9324ea37b78562.png)
[pop up box 2 at the bottom of wechat applet package]

jMeter使用案例

新手必会的静态站点生成器——Gridsome

web技术分享| 【高德地图】实现自定义的轨迹回放
Database mysql master-slave scheme
随机推荐
web技术分享| 【高德地图】实现自定义的轨迹回放
Blazor University (30) form - derived from inputbase
[pop up box at the bottom of wechat applet package] I
The way to optimize spark performance -- solving N poses of spark data skew
spark的NaiveBayes中文文本分类
你管这破玩意儿叫高可用?
高可用性的ResourceManager
[Alibaba cloud server - install MySQL version 5.6 and reinstall]
Docker 之MySQL 重启,提示Error response from daemon: driver failed programming external connectivity on **
MYSQL_ ERRNO : 1292 Truncated incorrect date value At add_ num :1
系统吞吐量、TPS(QPS)、用户并发量、性能测试概念和公式
有同学问PHP要学什么框架?
Test for API
[pop up box 2 at the bottom of wechat applet package]
mysql-5.6.21-centos6.5源码安装配置
快速掌握 ASP.NET 身份认证框架 Identity - 登录与登出
for.. of vs. for.. In statement
Is flush easy to open an account? Is it safe to open an account online?
JSP learning (2) -- JSP script elements and instructions
代码扫描工具扫出的 Arrays.asList 使用BUG