开发者

ASP.NET MVC: Restrict one Role per User

开发者 https://www.devze.com 2023-04-01 03:47 出处:网络
I am trying to create a program where that only one user can be in only one role at a time.I have developed a clunky means of removing the previously held role and then inserting the new role, but I d

I am trying to create a program where that only one user can be in only one role at a time. I have developed a clunky means of removing the previously held role and then inserting the new role, but I do not like t开发者_如何转开发his.

I attempted to do this at the database level, one-to-many instead of many-to-many in the UsersInRoles table but I only seem to only have success in breaking the 'built-in' role management system. Using System.Web.Security.SqlRoleProvider

Just feel there is a more elegant solution as I am new to MVC but I cannot think of it.

Anyone have a suggestion?


Why not do something like this. i.e. make it so adding a user to a role removes them from all others.

public class SingleRoleProvider : SqlRoleProvider
{
    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        // remove any existing roles users belong to
        RemoveUsersFromRoles(usernames, GetAllRoles());

        //only accept first role, your app should only be adding one at a time
        base.AddUsersToRoles(usernames, roleNames.Take(1));
    }
}


You obviously can't change the database schema and expect the default role provider to work. You will probably have to create a new one (you can use the source code available from MS to base your changes if you like).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号