Initializing RoleManager in ASP.NET Identity with Custom Roles

后端 未结 3 2051
渐次进展
渐次进展 2020-12-30 03:19

I changed the primary key for the user database from string to int using the tutorial here, but I\'m having difficulty initializing the Role Manager. It used to be initiali

3条回答
  •  無奈伤痛
    2020-12-30 03:33

    From your question i cannot determine if you are using the same frameworks (MVC & EF).

    Recently i have created an MVC + EF solution using custom ApplicationUsers & IdentityRoles. ApplicationUser is deriving from "Microsoft.AspNet.Identity.EntityFramework.IdentityUser". ApplicationRoles are implemented without changes.

    I have the following class:

    // Configure the used in the application. RoleManager is defined in the ASP.NET Identity core assembly
        public class ApplicationRoleManager : RoleManager
        {
            public ApplicationRoleManager(IRoleStore roleStore)
                : base(roleStore)
            {
            }
    
            public static ApplicationRoleManager Create(IdentityFactoryOptions options, IOwinContext context)
            {
                return new ApplicationRoleManager(new RoleStore(context.Get()));
            }
        }
    

    within configuration.cs (migrations)==> on 'update-database' this will be executed

        var roleStore = new RoleStore(context);
        var roleManager = new RoleManager(roleStore);
        var applicationRoleAdministrator = new IdentityRole("Administrator");
        if (!roleManager.RoleExists(applicationRoleAdministrator.Name))
        {
           roleManager.Create(applicationRoleAdministrator);
        }
    // do some logic to find your applicationUserAdministrator
    var applicationUserAdministrator = userManager.FindByName("Administrator");
    userManager.AddToRole(applicationUserAdministrator.Id, applicationRoleAdministrator.Name);
    

    withing startup.auth.cs the linkage towards the RoleManager:

    app.CreatePerOwinContext(ApplicationRoleManager.Create);
    

提交回复
热议问题