c# – ASP .NET MVC:如何更改用户的角色?

前端之家收集整理的这篇文章主要介绍了c# – ASP .NET MVC:如何更改用户的角色?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的应用程序中,我有一个管理员角色,这些类型的用户可以更改用户(客户端,经理……)的角色.我正在使用内置的会员提供商.这是我试图做的……
[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult EditRole(string usernameID,FormCollection formValues)
    {

        var db = new AppDataContext();
        var user = db.Users.SingleOrDefault(d => d.UserName == usernameID);
        string choosenRole = Request.Form["Roles"];                               

        var tuple = db.UsersInRoles.SingleOrDefault(d => d.UserId == user.UserId);
        var roleNameID = db.Roles.SingleOrDefault(d => d.RoleName == choosenRole).RoleId;
        tuple.RoleId = roleNameID;

        db.SubmitChanges();

        return RedirectToAction("Index");
    }

但是,我收到了这个错误..

Value of member ‘RoleId’ of an object of type ‘UsersInRole’ changed.
A member defining the identity of the object cannot be changed.
Consider adding a new object with new identity and deleting the existing one instead.

我被困了.有任何想法吗?

解决方法

您可以使用操作代码中提供的User,Roles和Membership静态类,而不是尝试直接从db(datacontext)访问成员资格表.

像这样:

System.Web.Security.Roles.AddUserToRole(usernameID,choosenRole);

假设您的usernameID是您要更改的用户的字符串键,并且choosenRole包含您要将用户添加到的角色名称键:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditRole(string usernameID,FormCollection formValues)
{
    string choosenRole = Request.Form["Roles"];                               
    System.Web.Security.Roles.AddUserToRole(usernameID,choosenRole);

    return RedirectToAction("Index");
}
原文链接:https://www.f2er.com/csharp/91490.html

猜你在找的C#相关文章