无法将角色分配给用户

时间:2018-11-17 10:09:44

标签: asp.net asp.net-mvc-5

我正在制作具有个人用户身份验证的ASP.NET MVC5应用程序。我可以创建用户,并且可以通过手动转到dbo.AspNetRoles并在其中键入内容来添加角色。我要做的是以编程方式将用户添加到dbo.AspNetUserRoles(其中UserId和RolesId作为列)。我正在尝试使用尽可能少的自定义类,例如,仅更改默认内容。我不知道如何将角色分配给用户。

1 个答案:

答案 0 :(得分:0)

请完整阅读本文: https://code.msdn.microsoft.com/ASPNET-MVC-5-Security-And-44cbdb97

以编程方式添加角色(将此方法添加到您的startup.cs中):

 private void createRolesandUsers()   
    {   
        ApplicationDbContext context = new ApplicationDbContext();   

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));   
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));   


        // In Startup iam creating first Admin Role and creating a default Admin User    
        if (!roleManager.RoleExists("Admin"))   
        {   

            // first we create Admin rool   
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();   
            role.Name = "Admin";   
            roleManager.Create(role);   

            //Here we create a Admin super user who will maintain the website                  

            var user = new ApplicationUser();   
            user.UserName = "shanu";   
            user.Email = "syedshanumcain@gmail.com";   

            string userPWD = "A@Z200711";   

            var chkUser = UserManager.Create(user, userPWD);   

            //Add default User to Role Admin   
            if (chkUser.Succeeded)   
            {   
                var result1 = UserManager.AddToRole(user.Id, "Admin");   

            }   
        }   

        // creating Creating Manager role    
        if (!roleManager.RoleExists("Manager"))   
        {   
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();   
            role.Name = "Manager";   
            roleManager.Create(role);   

        }   

        // creating Creating Employee role    
        if (!roleManager.RoleExists("Employee"))   
        {   
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();   
            role.Name = "Employee";   
            roleManager.Create(role);   

        }   
    } 

在注册后定义用户角色:

  await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles);