检查用户是否在 asp.net mvc Identity 中的角色

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

我在为我的数据库添加用户和角色时遇到问题。

User和Role都创建好了(报错后可以在数据库中看到)

但是,当我尝试检查用户是否在角色中时,出现异常。

我的代码是:

    public class tbInitializer<T> : DropCreateDatabaseAlways<tbContext>
    {
    protected override void Seed(tbContext context)
    {
        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);


        if(!userscontext.Users.Any(x=> x.UserName=="marktest"))
        {
            var user = new ApplicationUser { UserName = "marktest", Email = "marktest@gmail.com" };
            userManager.Create(user, "Pa$$W0rD!");
        }

        if (!roleManager.RoleExists("Admin"))
        { 
            roleManager.Create(new IdentityRole("Admin"));
        }

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

不过,就行了:

if(!userManager.IsInRole("marktest","Admin"))

异常抛出错误:UserId not found.

异常抛出后查看,User和Role都在数据库中:

谁能看出我做错了什么?

感谢您的帮助,

马克

我找到了解决方案,以防其他人遇到这个问题。

"IsInRole" 需要 User.Id - 而不是 UserName 字符串 - 所以我改为:

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

因此工作代码变为:

    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");
            }


    }

希望对您有所帮助,

马克

生活中最简单的事情;

bool isAdmin= User.IsInRole("admin") 

要添加到 Mark 的 post 上面,它在 .NET Core 3.1 Identity 中仍然几乎相同,唯一的区别是您必须传入 IdentityUser 类型对象的异步方法 IsInRoleAsync:

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

然后您可以在之后应用您的逻辑(在我的例子中,我做了两件事,首先检查角色是否确实存在,然后检查用户是否尚未分配给该角色)。