Home » forms authentication » ASP.NET Assigning a Role to a User

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"});

Like this Article? Subscribe to get every article sent to your email.

Related Post

  • Determine The Role of a User in ASP.NETDetermine The Role of a User in ASP.NET There are several controls that allow you to display content based on the role a user is in, including: - LoginView - LoginStatus And the web.config file allows us to control which […]
  • Authentication – Assigning Permissions to RolesAuthentication – Assigning Permissions to Roles Now that we’ve assigned roles to our users, we need to assign permissions to the roles. The easiest way to do this is through the web.config file, which will allow us to control which […]
  • ASP.NET Substitution ControlASP.NET Substitution Control Tucked away on the toolbar is a little-used and often overlooked control.  Not using this control could be costing you in performance. The control I’m referring to is the […]
  • Forms Authentication – Manual AuthenticationForms Authentication – Manual Authentication I’ve had several occasions in the past where I’ve needed to do my own authentication or I’ve needed to add some additional methods to the authentication process. As easy as Microsoft […]
  • Self Executing Anonymous FunctionSelf Executing Anonymous Function Not because it is all that new, but because it took me a while to find it, here’s how to create a self executing anonymous function using CSharp, just like you can do in JavaScript. […]

About Dave Bush

Dave Bush is a Full Stack ASP.NET developer. His commitment to quality through test driven development, vast knowledge of C#, HTML, CSS and JavaScript as well as his ability to mentor younger programmers and his passion for Agile/Scrum as defined by the Agile Manifesto and the Scrum Alliance will certainly be an asset to your organization.