Search code examples
.netasp.net-coreupgrade.net-framework-version

How to get list of user roles after upgrading from .NET framework to .NET Core?


Previously in .NET framework 4.6, my code to get role of specific user looked like this:

using System.Web.Security;

//......

var userRole = Roles.GetRolesForUser(userName);

// To get all roles:
var roles = Roles.GetAllRoles();

But after upgrading my web application project to .NET 6, I am in the process to fix dependencies and code in class libraries and I haven't found alternative for System.Web.Security.Roles so far.

I searched on Google but all I found was about Identity Roles using .NET Core but that will require db changes too so not looking forward to identity thing.

Please let me know about possible solutions.


Solution

  • You could inject the RoleManager and get roles like below in ASP.NET Core:

    public class TestController
    {
        private readonly RoleManager<IdentityRole> _roleManager;
    
        public TestController(RoleManager<IdentityRole> roleManager)
        {
            _roleManager = roleManager;
        }
    
        public void GetAllRoles()
        {
            var roles = _roleManager.Roles?.ToList();
        }
    }
    

    Be sure register the RoleManager in Program.cs(beyond .NET 5.0) or Startup.cs:

    services.AddIdentity<IdentityUser,IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();