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

2019-04-07 18:55发布

问题:

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.