It is best to use ready-made membership rather than creating an entirely new one for every application we create.
Let's start creating a MVC application first.
Creating MVC application
In Visual Studio select "File" -> "New" -> "Project...". A new wizard will be shown. Inside that select Visual C# Template and inside that Web and from the list of templates select ASP.NET MVC 4 Web Application then provide name for the project “MembershipDEMO”.
Then in the Project Templates select the Basic template.
After selecting Basic template then click on the OK button.
We have created a new project.
Adding Reference
Now we need to add a reference of
WebMatrix.Data and
WebMatrix.WebData.
For adding the reference right-click on References then select Add Reference.
WebMatrix.Data 2.0.0.0
WebMatrix.Data 2.0.0.0
After selecting just click on the OK button.
Then you will find the references have been add to your references folder.
Creating Database
Now create database in SQL Server with any name but I am naming it “UserDb” .
After creating the database now let's add the connection string.
Adding ConnectionString
Add the connection string in the Web.config file as in the following:
- <connectionStrings>
- <add name="DBConnection"
- connectionString="Data Source=saipc;Database=UserDb;UID=sa;Password=Pass$123" providerName= "System.Data.SqlClient" />
- </connectionStrings>
After adding the connection string now let's add Membership tables to the Userdb database.
For that we just need to add a line in Global.asax as in the following:
- WebSecurity.InitializeDatabaseConnection("DBConnection", "Users", "Id", "UserName", autoCreateTables:true);
After Ad3ding the Initialize Data3base Conne3ction now just run your application.
After running the application it will create all membership tables in the Userdb database.
Now we have tables with us that can store User Details and Roles. Now we need to create a UI for taking input from users.
Now we need to display data and get input. For that we need to create a Model first.
Adding Models
We will create 4 Models as in the following:
- AssignRoleVM
- Login
- Register
- Role
AssignRoleVM Model
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MembershipDEMO.Models
- {
- public class AssignRoleVM
- {
-
- [Required(ErrorMessage = "Enter Role Name")]
- public string RoleName { get; set; }
- [Required(ErrorMessage = "Enter User name")]
- public string UserName { get; set; }
- public List<SelectListItem> Userlist { get; set; }
- public List<SelectListItem> RolesList { get; set; }
- }
-
- public class AllroleandUser
- {
- public string RoleName { get; set; }
- public string UserName { get; set; }
-
- public List<AllroleandUser> AllDetailsUserlist { get; set; }
- }
-
- }
Login Model
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace MembershipDEMO.Models
- {
- public class Login
- {
- [Required]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
- public string password { get; set; }
-
- [Required(ErrorMessage = "Enter User name")]
- public string username { get; set; }
- }
- }
Register Model
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MembershipDEMO.Models
- {
- public class Register
- {
- [Required(ErrorMessage = "Enter Full Name")]
-
- public string FullName { get; set; }
- [Required(ErrorMessage = "Enter User name")]
-
- public string username { get; set; }
- [Required(ErrorMessage = "Enter EmailID")]
-
- public string EmailID { get; set; }
-
- [Required]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
- [DataType(DataType.Password)]
- [Display(Name = "Password")]
-
- public string password { get; set; }
-
-
- [DataType(DataType.Password)]
- [Display(Name = "Confirm password")]
- [Compare("password", ErrorMessage = "The password and confirmation password do not match.")]
- public string Confirmpassword { get; set; }
- }
- }
Role Model
- public class Role
- {
- [Required(ErrorMessage = "Enter Role name")]
- [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
- public string RoleName { get; set; }
- }
Now we have added the Model.
Adding Dapper Reference.
Now we will add a Dapper reference to the project because we need to get data from the database.
Its simple and easy to use.
For adding, just right-click on the project and select Manage Nuggets Package.
In the Search box type Dapper.
Inside this select Dapper dot net.
Created by: Sam Saffron, Marc Gravell.
Click on Install.
Now we have added Dapper. Let's move towards adding the Controllers.
Adding AccountController
First we will add an Account Controller.
The following is the code snippet of
AccountController:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using MembershipDEMO.Models;
- using WebMatrix.WebData;
-
- namespace MembershipDEMO.Controllers
- {
- public class AccountController : Controller
- {
-
- [HttpGet]
- public ActionResult Login()
- {
- return View();
- }
- }
- }
After adding the Controller now let's add a View to this Login Action Method.
Adding View (Login)
For adding the View just right-click inside the Action Method Login and select Add View. When you select Add View a new wizard will be shown. Inside this we will select Model class Login and Scaffolding as Create and finally click on the Add button.
Now save and run the application.
Displaying Error after running
You get the following error. Then you need to add some lines in Web.config:
Adding Membership related tags in Web.config
In Web.config under System.web:
- <membership defaultProvider="SimpleMembershipProvider">
- <providers>
- <clear />
- <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
- </providers>
- </membership>
- <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
- <providers>
- <clear />
- <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
- </providers>
- </roleManager>
Change Properties of Assembly for WebMatrix.Data and WebMatrix.WebData
Then you need to change the properties of the
WebMatrix.Data and
WebMatrix.WebData references.
Right-click on WebMatrix.Data and select Properties.
In properties change Copy Local to true.
You need to repeat that for WebMatrix.WebData.
Now run the application again.
Accessing Login page
Now we can see that we have the Login View. Now let's create its Login Post Method.
Code snippet for Login Action Method (Post)
In this method we will use a Login Model as input and then we are passing it to WebSecurity. Login to check that the Username and Password have been entered and is valid. If it is valid then we will redirect it to the Dashboard else to the same Login page.
- [HttpPost]
- public ActionResult Login(Login login)
- {
- if (ModelState.IsValid)
- {
- bool success = WebSecurity.Login(login.username, login.password, false);
- if (success)
- {
- string returnUrl = Request.QueryString["ReturnUrl"];
- if (returnUrl == null)
- {
- Response.Redirect("~/Home/index");
- }
- else
- {
- Response.Redirect(returnUrl);
- }
- }
- }
- else
- {
- ModelState.AddModelError("Error", "Please enter Username and Password");
- }
- return View(login);
-
- }
We have completed the Login part. Now let's move to the registration.
Adding Register Action Method
Now add another Action Method with the name Register.
- [HttpGet]
- public ActionResult Register()
- {
- return View();
- }
Adding View for Register Action Method
For adding the View just right-click inside Action Method Register and select Add View. When you select Add View a new wizard will be shown. Inside this we will select Model class Register and Scaffolding as Create and finally click on the Add button.
After creating Register View now just run the application and check.
Now run the application again.
Accessing Register pageNow we can see that we have a Register View. Now let's create the Register Post Method.
Code snippet for Register Action Method (Post)In this Action Method we will use the Register Model as input and using the built-in method of Membership WebSecurity.CreateUserAndAccount we will pass the Register Model to it and then redirect to the Login page.
- [HttpPost]
- public ActionResult Register(Register register)
- {
- if (ModelState.IsValid)
- {
- if (!WebSecurity.UserExists(register.username))
- {
- WebSecurity.CreateUserAndAccount(register.username, register.password,
- new { FullName = register.FullName, EmailID = register.EmailID });
- Response.Redirect("~/account/login");
- }
- }
- else
- {
- ModelState.AddModelError("Error", "Please enter all details");
- }
- return View();
- }
Until now we have added 4 Action Methods as in the following:
Now let's move to adding a Role.
Adding RoleCreate ActionMethod
The following adds the Action Method RoleCreate.
- [HttpGet]
- public ActionResult RoleCreate()
- {
- return View();
- }
Adding View for RoleCreate Action Method
After creating the Role View now just run the application and check.
Now run the application again.
Accessing RoleCreate page
Now we can see that we have the Role View. Now let's create the
Role Post Method.
Code snippet for RoleCreate Action Method (Post)
In this Action Method we will use a Role Model as input and then validate the Role using the Roles.RoleExists method to check whether or not the role name is already created. If yes then we will show an error Message else we will create the Role.
- [HttpPost]
- public ActionResult RoleCreate(Role role)
- {
- if (ModelState.IsValid)
- {
- if (Roles.RoleExists(role.RoleName))
- {
- ModelState.AddModelError("Error", "Rolename already exists");
- return View(role);
- }
- else
- {
- Roles.CreateRole(role.RoleName);
- return RedirectToAction("RoleIndex", "Account");
- }
- }
- else
- {
- ModelState.AddModelError("Error", "Please enter Username and Password");
- }
- return View(role);
- }
Now let's proceed to add RoleAddToUser.
Adding RoleAddToUser ActionMethod
In this Action Method we will fill 2 Dropdownlists, 1) Roles list 2) User list.
- [HttpGet]
- public ActionResult RoleAddToUser()
- {
- AssignRoleVM objvm = new AssignRoleVM();
-
- List<SelectListItem> listrole = new List<SelectListItem>();
-
- listrole.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Roles.GetAllRoles())
- {
- listrole.Add(new SelectListItem { Text = item, Value = item });
- }
-
- objvm.RolesList = listrole;
-
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))
- {
- var Userlist = con.Query("SELECT * FROM Users").ToList();
-
- List<SelectListItem> listuser = new List<SelectListItem>();
-
- listuser.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Userlist)
- {
- listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });
- }
-
- objvm.Userlist = listuser;
- }
-
- return View(objvm);
- }
We need to fill in the first Dropdownlist that is of Role.
- List<SelectListItem> listrole = new List<SelectListItem>();
- listrole.Add(new SelectListItem { Text = "Select", Value = "0" });
- foreach (var item in Roles.GetAllRoles())
- {
- listrole.Add(new SelectListItem { Text = item, Value = item });
- }
- objvm.RolesList = listrole;
We need to fill in the second Dropdownlist that is of User.
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBconnection"].ToString()))
- {
- var Userlist = con.Query("SELECT * FROM Users").ToList();
-
- List<SelectListItem> listuser = new List<SelectListItem>();
-
- listuser.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Userlist)
- {
- listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });
- }
-
- objvm.Userlist = listuser;
- }
Adding View for RoleAddToUser Action Method
For adding the View just right-click inside the Action Method RoleAddToUser and select Add View. When you select Add View a new wizard will be shown. Inside this we will select the Model class AssignRoleVM and Scaffolding as Create and finally click on the Add button.
After adding the View we need to change some code in the view by adding 2 dropdownlists to it.
After creating the RoleAddToUser View now just run the application and check.
Now run the application again.
Accessing RoleAddToUser page
Now we can see that we have the RoleAddToUser View. Now let's create its RoleAddToUser Post method.
Code snippet for RoleAddToUser Action Method (Post)
If you see, this action method is quite large.
Inside this we are first validating that the role and user dropdownlist is selected or not. If not then we will add the Model Error for it.
Then Validating that the role is already assigned to the user, if yes then add the Model Error else we will assign the Role to the user.
After adding we need to refill your Dropdownlist. For that we are re-populating it from the database.
Finally returning Model.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult RoleAddToUser(AssignRoleVM objvm)
- {
-
- if (objvm.RoleName == "0")
- {
- ModelState.AddModelError("RoleName", "Please select RoleName");
- }
-
- if (objvm.UserName == "0")
- {
- ModelState.AddModelError("UserName", "Please select Username");
- }
-
- if (ModelState.IsValid)
- {
-
- if (Roles.IsUserInRole(objvm.UserName, objvm.RoleName))
- {
- ViewBag.ResultMessage = "This user already has the role specified !";
- }
- else
- {
- Roles.AddUserToRole(objvm.UserName, objvm.RoleName);
-
- ViewBag.ResultMessage = "Username added to the role successfully !";
- }
-
-
- List<SelectListItem> lirole = new List<SelectListItem>();
- lirole.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Roles.GetAllRoles())
- {
- lirole.Add(new SelectListItem { Text = item, Value = item });
- }
-
- objvm.RolesList = lirole;
-
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString()))
- {
- var Userlist = con.Query("SELECT * FROM Users").ToList();
- List<SelectListItem> listuser = new List<SelectListItem>();
- listuser.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Userlist)
- {
- listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });
- }
- objvm.Userlist = listuser;
- }
-
- return View(objvm);
-
- }
-
- else
- {
- List<SelectListItem> lirole = new List<SelectListItem>();
- lirole.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Roles.GetAllRoles())
- {
- lirole.Add(new SelectListItem { Text = item, Value = item });
- }
-
- objvm.RolesList = lirole;
-
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString()))
- {
- var Userlist = con.Query("SELECT * FROM Users").ToList();
- List<SelectListItem> listuser = new List<SelectListItem>();
- listuser.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Userlist)
- {
- listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });
- }
-
- objvm.Userlist = listuser;
- }
- ModelState.AddModelError("Error", "Please enter Username and Password");
- }
- return View(objvm);
- }
Now let's procced to add DeleteRoleForUser.
Adding DeleteRoleForUser ActionMethod
In this action method I will delete the role for the User. For that I have 2 dropdownlists as in the following:
- Roles list
- User list
- [HttpGet]
- public ActionResult DeleteRoleForUser()
- {
- AssignRoleVM objvm = new AssignRoleVM();
-
- List<SelectListItem> lirole = new List<SelectListItem>();
- lirole.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Roles.GetAllRoles())
- {
- lirole.Add(new SelectListItem { Text = item, Value = item });
- }
-
- objvm.RolesList = lirole;
-
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))
- {
- var Userlist = con.Query("SELECT * FROM Users").ToList();
-
- List<SelectListItem> listuser = new List<SelectListItem>();
-
- listuser.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Userlist)
- {
- listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });
- }
-
- objvm.Userlist = listuser;
- }
-
- return View(objvm);
- }
Adding View for DeleteRoleForUser Action Method
For adding the View just right-click inside the Action Method DeleteRoleForUser and select Add View. When you select Add View a new wizard will be shown. Inside this we will select the Model class AssignRoleVM and Scaffolding as Empty and finally click on the Add button.
After adding the view just run application.
Accessing DeleteRoleForUser page
Code snippet for DeleteRoleForUser Action Method (Post)Inside this Action Method we will check whether the Dropdownlist is selected or not. Then we check if this User is in a Role. If it is in a role then we will only delete it else we will add an Error Message for it.
- [HttpPost]
- [ValidateAntiForgeryToken]
- public ActionResult DeleteRoleForUser(AssignRoleVM objvm)
- {
-
- if (objvm.RoleName == "0")
- {
- ModelState.AddModelError("RoleName", "Please select RoleName");
- }
-
- if (objvm.UserName == "0")
- {
- ModelState.AddModelError("UserName", "Please select Username");
- }
-
- List<SelectListItem> lirole = new List<SelectListItem>();
- lirole.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Roles.GetAllRoles())
- {
- lirole.Add(new SelectListItem { Text = item, Value = item });
- }
-
- objvm.RolesList = lirole;
-
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString()))
- {
- var Userlist = con.Query("SELECT * FROM Users").ToList();
-
- List<SelectListItem> listuser = new List<SelectListItem>();
-
- listuser.Add(new SelectListItem { Text = "Select", Value = "0" });
-
- foreach (var item in Userlist)
- {
- listuser.Add(new SelectListItem { Text = item.UserName, Value = item.UserName });
- }
-
- objvm.Userlist = listuser;
- }
-
- if (ModelState.IsValid)
- {
- if (Roles.IsUserInRole(objvm.UserName, objvm.RoleName))
- {
- Roles.RemoveUserFromRole(objvm.UserName, objvm.RoleName);
-
- ViewBag.ResultMessage = "Role removed from this user successfully !";
- }
- else
- {
- ViewBag.ResultMessage = "This user doesn't belong to selected role.";
- }
- }
-
- return View(objvm);
- }
After deleting the Roles for the User now let's proceed to delete the Role.
Adding another 2 Action Method RoleIndex and RoleDelete
For deleting roles I will use 2 Action Methods as in the following:
- for displaying roles RoleIndex
- for deleting roles that get role name as input
- public ActionResult RoleIndex()
- {
- var roles = Roles.GetAllRoles();
- return View(roles);
- }
-
- public ActionResult RoleDelete(string RoleName)
- {
- Roles.DeleteRole(RoleName);
- return RedirectToAction("RoleIndex", "Account");
- }
Adding View for RoleIndex Action Method
After adding the view now just run the application.
Accessing RoleIndex page
Now let's work with another Action Method RoleDelete.
Adding RoleDelete ActionMethod
When the user clicks on the Delete button it will call another method, RoleDelete, with Rolename as the input parameter.
When you click on delete it will ask for confirmation.
Accessing RoleDelete page
Now we have completed the deleting part of the role. Now let's move towards displaying all the lists of the User and roles.
Adding DisplayAllUserroles ActionMethod
Inside this action Method we will display all the Roles assigned to the user with their Username.
- [HttpGet]
- public ActionResult DisplayAllUserroles()
- {
- AllroleandUser objru = null;
- List<AllroleandUser> RUlist = new List<AllroleandUser>();
-
- ng (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mystring"].ToString()))
- {
-
- string Query = @"SELECT U.UserName,ro.RoleName FROM Users U
- Left JOIN webpages_UsersInRoles WU on U.Id = WU.UserId
- Left JOIN webpages_Roles ro on WU.RoleId = ro.RoleId";
-
- var RoleandUserList = con.Query(Query).ToList();
-
-
- foreach (var item in RoleandUserList)
- {
- objru = new AllroleandUser();
-
- if (item.RoleName == null)
- {
- objru.RoleName = "Role not Assign";
- }
- else
- {
- objru.RoleName = item.RoleName;
- }
-
- objru.UserName = item.UserName;
-
- RUlist.Add(objru);
- }
-
- objru.AllDetailsUserlist = RUlist;
- }
- return View(objru);
-
- }
Now first add the View for DisplayAllUserroles.
Adding View for DisplayAllUserroles Action Method
For that we are getting all the data from the database and adding to the list of
(List<AllroleandUser>) and sending the Model to the View.
After adding the view now just run the application.
Accessing DisplayAllUserroles page
Finally we have a bunch of Views.
Adding Logoff ActionMethod
- public ActionResult LogOff()
- {
- WebSecurity.Logout();
- Response.Redirect("~/Account/Login");
- return View();
- }
Now we need to create a Dashboard for displaying all this link of Roles.
Adding Controller Dashboard
Code snippet for DashboardController.
Then add a View Index by right-clicking inside the View with an Empty Model.
- namespace MembershipDEMO.Controllers
- {
- public class DashboardController : Controller
- {
- [Authorize(Roles = "Admin")]
- public ActionResult Index()
- {
- return View();
- }
-
- }
- }
Code snippet of Index ActionMethod of DashboardController
The following is the link that we have added to the Dashboard View:
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- <h3>Roles Management</h3>
- <ol class="round">
- <li class="one">
- @Html.ActionLink("List of all roles", "RoleIndex", "Account")
- </li>
-
- <li class="two">
- @Html.ActionLink("Assign Role To User", "RoleAddToUser", "Account")
- </li>
-
- <li class="three">
- @Html.ActionLink("CreateRole", "RoleCreate", "Account")
- </li>
-
- <li class="four">
- @Html.ActionLink("DeleteRole", "DeleteRoleForUser", "Account")
- </li>
-
- <li class="five">
- @Html.ActionLink("List of all roles Assign to User", "DisplayAllUserroles", "Account")
- </li>
- </ol>
Accessing Index page of DashboardController
Finally we need to add the Home Controller and make it the landing page after login.
Adding Controller Home
Code snippet for HomeController.
- namespace MembershipDEMO.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
- }
- }
Adding View for Index Action Method
Finally the output of the Homepage with the Roles Management link on it.
Accessing Index page of HomeControllerTip: Restrict Action and Controller with Authorize Attribute.
If you want to restrict the user of a specific role to some Action method then add an Authorize Attribute to it with the Role Name you want to restrict.
For Example:
- [Authorize(Roles = "Admin")]
Restrict Controller
- [Authorize(Roles = "Admin")]
- public class DashboardController : Controller
- {
- return View();
- }
Restrict Action Method
- [Authorize(Roles = "Admin")]
- public ActionResult Index()
- {
- return View();
- }
Thanks for reading this article. I Hope you have gotten how to use membership in ASP.NET MVC 4.
I made it as simple as possible and tried to explain every bit of code. Implement it and add comments to this article.
Finally we have completed Membership in ASP.NET MVC 4.