Creating Roles in Asp.net Identity MVC 5

前端 未结 11 1382
情深已故
情深已故 2020-12-02 05:09

There is very little documentation about using the new Asp.net Identity Security Framework.

I have pieced together what I could to try and create a new Role and add

11条回答
  •  旧巷少年郎
    2020-12-02 05:54

    the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.

    string [] roleNames = { "role1", "role2", "role3" };
    var RoleManager = new RoleManager(new RoleStore(context));
    
                    IdentityResult roleResult;
                    foreach(var roleName in roleNames)
                    {
                        if(!RoleManager.RoleExists(roleName))
                        {
                            roleResult = RoleManager.Create(new IdentityRole(roleName));
                        }
                    }
                    var UserManager = new UserManager(new UserStore(context));
                    UserManager.AddToRole("user", "role1");
                    UserManager.AddToRole("user", "role2");
                    context.SaveChanges();
    

提交回复
热议问题