How do you rename a Role using Membership in .NET?

女生的网名这么多〃 提交于 2020-01-01 09:45:09

问题


I'm using ASP.NET Membership and noticed there isn't a method in the Roles class to modify a role (its name for instance), only to create and delete them.

Is it possible or it's not supported?

EDIT: @CheGueVerra: Yes, nice workaround.

Do you know (for extra credit :) ) why it's not possible?


回答1:


There is no direct way to change a role name in the Membership provider.

I would get the list of users that are in the role you want to rename, then remove them from the list, delete the role, create the role with the new name and then Add the users found earlier to the role with the new name.

public void RenameRoleAndUsers(string OldRoleName, string NewRoleName)
{
    string[] users = Roles.GetUsersInRole(OldRoleName);
    Roles.CreateRole(NewRoleName);
    Roles.AddUsersToRole(users, NewRoleName);
    Roles.RemoveUsersFromRole(users, OldRoleName);
    Roles.DeleteRole(OldRoleName);
}

That will change the name of the role for all users in the role.

Follow-up: Roles, are used to ensure a user plays only his part in the system, thus User.IsInRole(ROLE_NAME), will help you enforce the BR securities that apply, for a user and the roles he is in. If you can change the role names on the fly, how are you going to validate that the user is really in that role. Well that's what I understood, when I asked about it.

rtpHarry edit: Converted pseudocode sample to compilable c# method




回答2:


Renaming a Role in the ASP.NET Membership model programatically would be a Bad Thing™, because the Role names are used in the configuration file to define permissions. If there were a programmatic way to change the Role name (which persisted the change to the database), you would immediately break any Role-based security configurations in web.config for any web apps using the database, and there'd be no way to guarantee that a single web app could alter the configuration of every web app using that Membership DB.



来源:https://stackoverflow.com/questions/281891/how-do-you-rename-a-role-using-membership-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!