添加前检查用户角色是否存在

Checking role exists for user before add

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

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

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

你只需要勾选User.IsInRole("YourRoleName");

如果您想通过 User Id 进行检查,请使用以下代码。

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