Search code examples
c#asp.net-mvcasp.net-identityroles

Checking role exists for user before add


I am trying to add roles for user but before that i want to check it is exists or not. How Can i do that? Here is my code

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

for example i have a user and its id =1. When i add role for this user i want to check there is a role for this user before add new role to this user


Solution

  • You just need to check User.IsInRole("YourRoleName");

    If you want to check by User Id, use the code below.

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