Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove User from Roles in ASP.NET Identity 2.x

How can I remove User from Roles in ASP.NET Identity 2.x ? about adding role to user there is no problem but when I want to remove a role from a user I cannot.It should be mentioned that there is no exception or error!

//POST: Admin/User/Edit/5
    [AcceptVerbs(HttpVerbs.Post)]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Prefix = "")]UserViewModel userViewModel, List<int> availableRoles)
    {
        if (ModelState.IsValid)
        {
            List<int> newListOfRolesIDs = availableRoles;
            List<int> oldListOfRolesIDs = UserBLL.Instance.GetRolesIDs(userViewModel.Id);
            List<int> deletedList;
            List<int> addedList;
            var haschanged = oldListOfRolesIDs.ChangeTracking(newListOfRolesIDs, out deletedList, out addedList);
            using (new EFUnitOfWorkFactory().Create())
            {
                if (haschanged)
                {
                    UserBLL.Instance.InsertRoles(addedList, userViewModel.Id);
                    UserBLL.Instance.DeleteRoles(deletedList, userViewModel.Id);
                }
                await UserBLL.Instance.UpdateAsync(userViewModel);
            }
            //ArticleBLL.Instance.UpdatePartial(articleViewModel,  m => m.Title);
            return RedirectToAction("Edit");
        }
        return View(userViewModel);
    }

Delete Role method:

public void DeleteRoles(List<int> deleteList, int? userId)
    {
        if (userId != null)
        {
            User user = UserManager.FindByIdAsync(userId.Value).Result;
            foreach (var i in deleteList)
            {
                user.Roles.Remove(new UserRole { RoleId = i, UserId = user.Id }); // What's the problem?!
            }
        }
    }

Insert Role method:

public void InsertRoles(List<int> insertList, int? userId)
    {
        if (userId != null)
        {
            User user = UserManager.FindByIdAsync(userId.Value).Result;
            foreach (var i in insertList)
            {
                user.Roles.Add(new UserRole { RoleId = i, UserId = user.Id });
            }
        }
    }
like image 626
Roohi Avatar asked Dec 05 '22 04:12

Roohi


2 Answers

What you are looking for is the RemoveFromRoleAsync method. An example would look similar to the following:

public async Task DeleteRolesAsync(List<string> deleteList, int? userId)
{
    if (userId != null)
    {
        foreach (var roleName in deleteList)
        {
            IdentityResult deletionResult = await UserManager.RemoveFromRoleAsync(userId, roleName);
        }
    }
}

If you already have the ID of the user, there's no need to get the user again (only if you want to make sure that the user really exists; then you have to wrap your foreach with an if-statement). The deletion methods needs the name of the role, instead of the ID, to delete the user from the role. You can use the result of the operation (in my example stored in deletionResult) to make sure that the operation was successful. Remember that the name of the user manager (in my example UserManager) can vary depending on your implementation.

like image 63
Horizon_Net Avatar answered Dec 06 '22 19:12

Horizon_Net


I had the same issue and what I ended up using was the RemoveFromRolesAsync(string userId, params string[] roles) Method from the UserManager.

Using the role names in an array works. But has an issue that is if the user is not in one of the roles in the array the user will not be removed from any roles in the array. All or nothing.

            var usr = UserManager.FindById(usrV.ID.ToString());

            string[] deleteList;
            deleteList= new string[1];
            deleteList[0] = "Engineer";

            var rresult1 = UserManager.RemoveFromRolesAsync(usr.Id, deleteList);

Hope it helps

like image 30
The BitMaster Avatar answered Dec 06 '22 19:12

The BitMaster