Using the UserManager service in .net core

If you have used a template to set up razor pages with authentication, you may need to address the UserManager service directly.

Injecting the service in the model.

In this first example, we inject the UserManager service using the constructor of the Razor Page Model. We assign it to a private field _userManager. Then we can use _userManager to find out if the current user is in the admin role.

 public class DemoModel : PageModel
        private readonly Users.Data.UsersContext _context;
        private readonly UserManager<IdentityUser> _userManager;
        public DemoModel(Users.Data.UsersContext context, UserManager<IdentityUser> userManager)
            _context = context;
            _userManager = userManager;

        public async Task<IActionResult> OnGetAsync(int? id)
             String userName = User.Identity.Name;
             var user = await _userManager.FindByEmailAsync(userName);
              Boolean isadmin = await _userManager.IsInRoleAsync(user, "admin");
              if (isadmin) {
                     // do some things

Injecting the service in the razor page

However, what if you want to check directly on the razor page itself? For, example, you may have a partial page, and no model? In this case we inject the service directly.

@inject UserManager<IdentityUser> _userManager
<h2>This is my razor page.</h2>
             Boolean isadmin = false; 
             if (User.Identity.IsAuthenticated) {
                        var user = await _userManager.FindByEmailAsync(User.Identity.Name);
                         isadmin = await _userManager.IsInRoleAsync(user, "admin");
                 if (isadmin)
                        <p> Present some link or information just for admin users </p>

Creating roles

If you don’t have roles set up, it can be easier just to create them directly in your SQL Server database, since you won’t be repeating the process. Then go to your register code and add a line to assign the role at the point of registration. In this case, I assign the user the role of “student”.

 await _userManager.AddToRoleAsync(user, "student");

Leave a Reply

Your email address will not be published. Required fields are marked *