Checking if a user is in a role in asp.net mvc Identity

前端 未结 3 496
你的背包
你的背包 2020-12-31 02:23

I\'m having an issue seeding my database with users and roles.

The User and the Role are both created (I can see them in the database after the error is thrown).

相关标签:
3条回答
  • 2020-12-31 02:52

    I found out the solution, in case anyone else is having this problem.

    The "IsInRole" is expecting a User.Id - not a UserName string - so I changed to:

                if (!userManager.IsInRole(user.Id, "Admin"))
                {
                    userManager.AddToRole(user.Id, "Admin");
                }
    

    So the working code becomes:

        ApplicationDbContext userscontext = new ApplicationDbContext();
        var userStore = new UserStore<ApplicationUser>(userscontext);
        var userManager = new UserManager<ApplicationUser>(userStore);
    
        var roleStore = new RoleStore<IdentityRole>(userscontext);
        var roleManager = new RoleManager<IdentityRole>(roleStore);
    
        // Create Role
        if (!roleManager.RoleExists("Admin"))
        { 
            roleManager.Create(new IdentityRole("Admin"));
        }
    
        if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
        {
            // Create User
            var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" };
            userManager.Create(user, "Pa$$W0rD!");
    
            // Add User To Role
            if (!userManager.IsInRole(user.Id, "Admin"))
                {
                    userManager.AddToRole(user.Id, "Admin");
                }
    
    
        }
    

    I hope that helps,

    Mark

    0 讨论(0)
  • 2020-12-31 03:03

    To add to Mark's post above in its still pretty much the same in .NET Core 3.1 Identity only difference with the async method IsInRoleAsync you have to pass in the IdentityUser type object:

    var userInRole = await _userManager.IsInRoleAsync(user, role);
    

    Then you can apply your logic afterwards (in my case I was doing two things, first checking the role actually exists and then checking if the user isn't already assigned to that role).

    0 讨论(0)
  • 2020-12-31 03:08

    Simplest thing in life;

    bool isAdmin= User.IsInRole("admin") 
    
    0 讨论(0)
提交回复
热议问题