本文介绍了UserManager.RemoveFromRoles不删除角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditUser(AspNetUser UserToEdit, string[] roles)
        {
            AspNetUser CurrentUser = db.AspNetUsers.Find(User.Identity.GetUserId());
            AspNetUser UserBeingEdited = db.AspNetUsers.Find(UserToEdit.Id);

            string[] AllRoles = db.AspNetRoles.Select(s => s.Name).ToArray();
            UserManager.RemoveFromRoles(UserBeingEdited.Id, AllRoles);


            // Add all of the roles returned from the webpage
            if (roles.Count() > 0)
            {
                UserManager.AddToRoles(UserBeingEdited.Id, roles);
            }
        }

运行此代码后,我检查用户,该用户仍然具有以前的角色.角色是从我的编辑用户页面返回的角色列表,并且已正确填充.

After I run this code I check the user and the user still has the same roles they had before. roles is a list of roles returned from my edit user page and it is populated correctly.

任何人都知道如何使它正常工作吗?没有错误或其他任何东西.

Anyone know how to get this to work? No errors or anything.

推荐答案

我认为问题出在从所有可用角色而不是从用户拥有的角色中删除用户时.

I think that problem is when you are removing user from all available roles, not from roles that user has.

尝试一下,

[HttpPost]
[ValidateAntiForgeryToken]
    public ActionResult EditUser(AspNetUser UserToEdit, string[] roles)
    {
        // Get user roles
        string[] allUserRoles = UserManager.GetRoles(UserToEdit.Id).ToArray();
        UserManager.RemoveFromRoles(UserToEdit.Id, allUserRoles);

        // Add all of the roles returned from the webpage
        if (roles.Count() > 0)
        {
            UserManager.AddToRoles(UserToEdit.Id, roles);
        }
    }

这篇关于UserManager.RemoveFromRoles不删除角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 12:33