Introduction
This article is the continuation of the article “Registration Razor Page in ASP.NET Core Razor Pages Web Application”. In this article, we will be creating different roles for our application. We will work on different kinds of roles that we can assign to each user using this application.
Creating Roles for the application
We have two types of users in the application I created in the previous article. We will create two types of users to login through the registration form created in the previous article. The users will be admin and customer users. As we worked on the create function to create a new user, now we will work on different kinds of roles that we can assign to each user trying to create an account in this particular application.
Let’s add two roles in our database. In order to add roles, we can create a static class. To create a class, right-click on the project, click on Add and then select folder. This will add a new folder named utility.
Now right click on the utility folder. Click on add, then select class option to add a static class named sd.
This class will contain all the constants:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- namespace SparkAutomation.Utility
- {
- public class SD
- {
- public const string AdminEndUser = "Admin";
- public const string CustomerEndUser = "Customer";
- }
- }
Next, we add constants to different types of roles for the website. The two constants are AdminEndUser and CustomerEndUser.
Now in our application, if we want to login as admin we can reference to AdminEndUser and if we want to login as a customer we can reference to CustomerEndUser inside a static class.
Now inside the registration form, when a new user is added we can make them admin for a default scenario.
We can create a new user inside the post handler. Inside the post hander, we have to create an application user and we have to assign all of the properties as well such as username, email, name, address, city, postal code, and phone number.
- var user = new ApplicationUser
- {
- UserName = Input.Email,
- Email = Input.Email,
- Name = Input.Name,
- Address = Input.Address,
- City = Input.City,
- PostalCode = Input.PostalCode,
- PhoneNumber = Input.PhoneNumber
- };
Now once a user is created, we can create roles as well. In order to add roles, we have to get role manager using dependency injection. While saving changes inside database for any newly created use of database object as well.
- private readonly RoleManager<IdentityRole> _roleManager;
- private readonly ApplicationDbContext _db;
We have to add them inside RegisterModel constructor as follows.
- public RegisterModel(
- UserManager<IdentityUser> userManager,
- SignInManager<IdentityUser> signInManager,
- ILogger<RegisterModel> logger,
- IEmailSender emailSender,
- RoleManager<IdentityRole> roleManager,
- ApplicationDbContext db)
- {
- _userManager = userManager;
- _signInManager = signInManager;
- _logger = logger;
- _emailSender = emailSender;
- _db = db;
- _roleManager = roleManager;
- }
Here, we are adding two read only properties inside dependency injection, which are roleManager and ApplicationDbContext.
Inside the post handler, when the user is created we are checking if the roles exist in the database or not. If the user does not exist, we can create it for both admin and customer using the below line of code.
- if (result.Succeeded)
- {
- if (!await _roleManager.RoleExistsAsync(SD.AdminEndUser))
- {
- await _roleManager.CreateAsync(new IdentityRole(SD.AdminEndUser));
- }
- if (!await _roleManager.RoleExistsAsync(SD.CustomerEndUser))
- {
- await _roleManager.CreateAsync(new IdentityRole(SD.CustomerEndUser));
- }
When these lines gets executed, they will create new roles inside database. Once a role is create we can assign it to the user using below line of code.
- await _userManager.AddToRoleAsync(user,SD.AdminEndUser);
We have to add the IdentityRole to the pipeline inside the startup.cs file so that the application will run properly.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options =>
- options.UseSqlServer(
- Configuration.GetConnectionString("DefaultConnection")));
- services.AddIdentity<IdentityUser,IdentityRole>()
- .AddDefaultTokenProviders()
- .AddDefaultUI()
- .AddEntityFrameworkStores<ApplicationDbContext>();
- services.AddRazorPages().AddRazorRuntimeCompilation();
- }
Now IdentityRole will be added and configured inside the application.
Register.cshml.cs




ronald balkPosted Apr 6, 2022, 8:03 AM
Perfect. adding var user = new ApplicationUser was essential
Jeremy MwangelwaPosted Feb 2, 2021, 3:22 AM
Thank you so much. You have helped me a lot! Had to change a few things in services. I'm not sure if that's a Microsoft thing or not. Here's a working example: https://github.com/jeremycoder/SparkAutomation
Jeremy MwangelwaPosted Feb 2, 2021, 3:16 AM
Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddRoles<IdentityRole>() .AddDefaultTokenProviders() .AddDefaultUI() .AddEntityFrameworkStores<ApplicationDbContext>();
pspPosted Jul 12, 2020, 2:03 PM
Hi Abhishek. I have trouble making it run. Could you please upload complete code?
Inzi BhaiPosted Jun 4, 2020, 1:57 AM
Hi, Can you upload code for complete example also