ASP.NET Web Pages – Add Roles

[ This is a 5 part tutorial ]

Previously we have covered how the membership system works; there are many features you can add to your website. We can also add roles which allow us to create an access level based on that user’s role (or rank). For example, for standard users and administrators we will cover the following:

  • Create Roles
  • Add Users to Roles
  • Remove Users from Roles
  • Delete Roles

Roles are useful for restricting certain parts of your website. For example, you might have standard users who can edit content and then you might have administrators who can edit and delete content as well as see user information.

  1. Create a new site based of the Startersite template and leave it with the default name
  2. Add a folder called Private in the root directory
  3. Add a _PageStart file and set the layout, and restrict it to logged in users only
  4. Add another file called AddRole
  5. Run the website and register yourself

Add Roles

Now in the add roles file copy this code:



 var msg = "";
 var role = Request["role"];

    var roles = Roles.GetAllRoles();

   if (IsPost){
       if (!role.IsEmpty()){//MAKE SURE ROLE IS NOT EMPTY
           if(!Roles.RoleExists(role)){//MAKE SURE ROLE DOES NOT EXIST
               Roles.CreateRole(role);//CREATE THE ROLE
               msg  = role +" has been created";
               msg = role + " already exist!";



First we create two global variables. We then create a variable called roles which is set to retrieve the current created roles. We will output these in an unordered list, and then on post we process the data. The validation class has not been used this time, but we still make sure that the HTML field role is not empty. We then make sure the role does not exist, and finally we create the role.


For the sake of brevity the HTML will not be explained.

<form method="post">    


    <legend>Add Role</legend>
        <input type="text" name="role" />
        <input type="submit" value="Add Role"/>


@foreach (var userRoles in roles){



Now make a new role called Admin.

[ Continue, add user to role ]