简体   繁体   English

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

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

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).用户和角色都创建了(我可以在抛出错误后在数据库中看到它们)。

However, when I try to check if the user is in a role, I get an exception.但是,当我尝试检查用户是否在某个角色中时,出现异常。

My code is:我的代码是:

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

However, on the line:然而,上线:

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

An exception is thrown with the error: UserId not found.引发异常并显示错误: UserId not found.

The User and the Role are both in the database when I check after the exception is thrown:当我在抛出异常后检查时,用户和角色都在数据库中:

显示用户添加到数据库

显示添加到数据库的角色

Can anyone see what I'm doing wrong?谁能看到我做错了什么?

Thanks for any help,谢谢你的帮助,

Mark标记

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: “IsInRole”需要一个 User.Id - 而不是 UserName 字符串 - 所以我改为:

            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标记

生活中最简单的事;

bool isAdmin= User.IsInRole("admin") 

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:要添加到上面 Mark 的帖子中,它在 .NET Core 3.1 Identity 中仍然几乎相同,仅与异步方法 IsInRoleAsync 不同,您必须传入 IdentityUser 类型对象:

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).然后你可以在之后应用你的逻辑(在我的例子中我做了两件事,首先检查角色实际存在,然后检查用户是否尚未分配给该角色)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM