User Registration with ASP.NET Core Identity

发布时间 2023-07-13 14:44:46作者: ChuckLu

User Registration with ASP.NET Core Identity

So basically, we have all the input fields from our model in this view. Of course, clicking the Create button will direct us to the POST Register method with the UserRegistrationModel populated.

Now, let’s install the AutoMapper library, so we could map the UserRegistrationModel to the User class:

 

As you can see, the action is async now because the UserManager’s helper methods are async as well. Inside the action, we check for the model validity and if it is invalid, we just return the same view with the invalid model.

If that check passes, we map the registration model to the user.

Additionally, we use the CreateAsync method to register the user. But this method does more for us. It hashes a password, executes an additional user checks and returns a result.

If the result is successful, we just attach the default role to the user, again with the UserManager’s help, and redirect the user to the Index page.

But if the registration fails, we loop through all the errors and add them to the ModelState.

 

创建的用户保存到了AspNetUsers用户表,并且添加了默认的role,会在AspNetUserRoles添加用户和角色的关系。

 

Identity Options

As you could see in the testing example, our user registration process requires a password to fulfill certain rules. These rules can be found and adjusted in the IdentityOptions settings.

Right now, the password requires at least 6 characters, upper and lower case letters, etc.

Let’s play around a bit with these values.