2012-08-13

How to programmatically add users and assign them to roles in asp.net membership provider

First of all we have to import the Security namespace as below

using System.Web.Security;

By using the below line, we can create users programmatically. Below I’m creating a user named “Ruchira” with password “Password”.

MembershipUser newUser = Membership.CreateUser("Ruchira", "Password");

By using the below line, we can programmatically assign the user to a particular role. Here I’m assigning the user named “Ruchira” (Which I created above) to the role named “RoleName”

Roles.AddUserToRole("Ruchira", "RoleName");

So altogether, the code would be looks like below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            MembershipUser newUser = Membership.CreateUser("Ruchira", "Password");
            Roles.AddUserToRole("Ruchira", "Role");
        }

    }
}

1 comment:

Ramesh Kumar said...

Thanks for sharing this useful info.keep updating same way.
Cheers,
RK
Smart Phone Apps Development Company