在添加之前,用户存在检查角色

Fat*_*mov 3 c# asp.net-mvc roles asp.net-identity

我正在尝试为用户添加角色但在此之前我想检查它是否存在.我怎样才能做到这一点?这是我的代码

  public void AddRoleForUser(ApplicationUser obj, IdentityRole role)
    {
        _userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(_context));

        var currentUser = _userManager.FindById(obj.Id);
        // before this i have to check 
        var roleresult = _userManager.AddToRole(currentUser.Id, role.Name);
    }
Run Code Online (Sandbox Code Playgroud)

例如,我有一个用户,其id = 1.当我为该用户添加角色时,我想在向该用户添加新角色之前检查该用户是否有角色

Bas*_*tia 5

你只需要检查一下 User.IsInRole("YourRoleName");

如果您想查看User Id,请使用以下代码.

if (!userManager.IsInRole(user.Id, "Admin"))
{
    userManager.AddToRole(user.Id, "Admin");
}
Run Code Online (Sandbox Code Playgroud)