ASP.NET Assigning a Role to a User

C03H0045

Another function that is not supplied by one of the existing controls in ASP.NET is the ability to assign a user to a role.  For this, we will need to resort to using the APIs.

Since we can assign roles to users using the ASP.NET configuration tool, we can assume there is an API available that will do this work for us.

Here is how it is done.

The first  thing we will need to do is to add the roles to the system.  The API for this is pretty simple.

using System.Web.Security;

if (!Roles.RoleExists("RoleName"))
{
  Roles.CreateRole("RoleName"));
}

To attach a user to the role, you call AddUsersToRole.  You can add multiple users and/or multiple roles at the same time.

Roles.AddUserToRole("User","Role");

// or

Roles.AddUserToRole("User", new string[]
    {"role1","role2"});

// or

Roles.AddUserToRole(new string[]
    {"user1","user2"},"role");

// or

Roles.AddUserToRole(
    new string[] {"user1","user2"},
    new string[] {"role1","role2"});

Related Post

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear