Noor
Noor

Reputation: 305

How To Implement .Net Core Identity on Asp.Net Core 5.0 Project Following Repository Pattern?

I am working on the .Net Core 5.0 technology and my current project structure is as follow (In the same solution):

  1. Asp.Net Core 5.0 Web API Project
  2. Asp.Net Core 5.0 Web Application Project For Admin Users (Client-Side)
  3. Asp.Net Core 5.0 Web Application Project For Super Admin (Client-Side)
  4. Asp.Net Core 5.0 Class Library (For Repository Pattern)

The Web API project is simply an API project that will respond to Admin/Super Admin Client applications by providing resources for database operations (Crud Operation).

The Repository Project is where the whole of my application logic exists including Interfaces and their implementations. The repository pattern is injected on API Controllers where the controller method performs the particular operation using the UnitOfWork pattern of the Repository Project.

I have implemented .Net Core Identity (Not Scaffolded Identity, I have just inherited the ApplicationContext class of repository pattern from IdentityDbContext while passing the custom AppliationUser class to it) on the repository project and everything works fine even after running the code first migration for adding identity tables and customizing the IdentityUser.

What I want to achieve is to use Identity Scaffolding on both of my client applications (For Admin and Super Admin Portals), in order to allow Super Admin for adding Roles and assigning Users to those Roles.

With the Admin portal, I will be allowing Admins to manage their own users.

However, I am facing issues in dealing with the startup.cs part on each of my Admin and Super Admin portals. I do want to use only the ApplicationContext.cs class on Repository Project for all of my Database related operations. But, scaffolding the identity (on Super Admin portal results in creating a data folder with a separate AppliationDbContext.cs class and migrations folder) and most probably this will be the case with the Admin portal (I didn't try it on the Admin portal).

Note: I have scaffolded the identity on the Super Admin portal using Command Line Interface (CMD) because VS19 throws an error when I try to scaffold identity by right-clicking on the project and choosing to add scaffolding).

What I need now is to use the Identity tables like the Roles table for allowing Super Admin to create new roles. But when I try to run my project and execute the code where Super Admin creates a role, it shows me an error in the popup/alert box window saying:

enter image description here

Here is my code for saving the role using ajax call to my API project:

function SaveRole() {
        
        var roleName = $('#roleName').val();

        $.ajax({
            url: APIHost + 'api/SuperAdmin/AddNewRole',
            data: JSON.stringify(roleName),
            type: 'POST',
            contentType: 'application/json;charset=utf-8',
            dataType: 'json',
            success: function (result) {
                if (result) {
                    $("#closeNewRoleModal").click();
                }
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

And API SuperAdmin Controller code:

    [Route("api/SuperAdmin")]
        [ApiController]
        public class SuperAdminController : ControllerBase
        {
            private readonly IUnitOfWork _unitOfWork;
            private RoleManager<IdentityRole> _roleManager;
            private UserManager<ApplicationUser> _userManager;
            public SuperAdminController(IUnitOfWork unitOfWork, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
            {
                _unitOfWork = unitOfWork;
                _roleManager = roleManager;
                _userManager = userManager;
            }
    
            [HttpPost]
            [Route("AddNewRole")]
            public async Task<IActionResult> AddNewRole(string role)
            {
    
                await _roleManager.CreateAsync(new IdentityRole(role));
                  
                return new JsonResult(true);
            }
       }

Update:

I have removed the Data Folder and Migrations Folder added by Identity Scaffolding. And on the startup.cs class of my Super Admin portal, I am doing this on the ConfigureServices method:

services.AddDbContext<ApplicationContext>();
            services.AddIdentity<ApplicationUser, IdentityRole>()
                    .AddEntityFrameworkStores<ApplicationContext>()
                    .AddDefaultTokenProviders();

Please note that the ApplicationContext is the actual context class within Repository Project which I am using for database operations and is inherited from the IdentityDbContxt base class.

Upvotes: 0

Views: 206

Answers (1)

Noor
Noor

Reputation: 305

It was my mistake that I was completely avoiding the startup.cs class of Super Admin portal. I thought that each application will be using the startup.cs class of API Project.

I included the following code in ConfigureServices method on my Admin Portal's startup.cs class and the issue was resolved:

services.AddDbContext<ApplicationContext>();

services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationContext>()
        .AddDefaultTokenProviders()
        .AddDefaultUI();

Upvotes: 0

Related Questions