Search code examples
c#asp.netasp.net-mvcasp.net-mvc-5asp.net-identity-2

Remove all Roles from a user MVC 5


Peace be upon you

I am trying to remove all roles from a user to disable his permissions and prevent him from accessing some pages.

I found this method to remove one role and it worked:

await UserManager.RemoveFromRoleAsync(userid, role);

Where userid is the user ID that I want to disable his permission.

So, I use this code to delete all roles from the same user

foreach (string role in roles) {

 await UserManager.RemoveFromRoleAsync(userid, role);

}

But I stuck here how to save roles Id which are in AspNetRoles table to

string[] roles 

Any help?

or is there another way to delete all roles from a user?

I am using asp.net identity version 2


Solution

  • User manager has a method Task<IList<string>> GetRolesAsync(TKey userId) which

    Returns the roles for the user

    And also Task<IdentityResult> RemoveFromRolesAsync(TKey userId, params string[] roles) that

    Remove user from multiple roles

    so combine the two to achieve what you want

    var roles = await UserManager.GetRolesAsync(userid);
    await UserManager.RemoveFromRolesAsync(userid, roles.ToArray());