Back to: ASP.NET MVC Tutorial For Beginners and Professionals
Create a User Account in ASP.NET Identity
In this article, I am going to discuss Creating a User Account in ASP.NET Identity. Please read our previous article, where we discussed Customizing ASP.NET Identity Tables with EF Code-First Approach.
Create a User Account in ASP.NET Identity
In order to create a new user account using ASP.NET Identity, we need to use the Create or CreateAsync method.
Create or CreateAsync Method:
If you go to the definition of the Register HTTP post method of the Account Controller class, then you will see that by default, it uses the following CreateAsync method to create a new user account using ASP.NET Identity.
As you can see in the above code, the Create method will create the user, which is passed as a parameter of the method with the given password and returns the result of the operation as an IdentityResult object. Here, instead of the CreateAsync method, you can also use the Create method to create a new user account as follows.
The Create method is called by the ApplicationUserManager, which performs user-related operations. It is also possible to create a user account with no password. Whenever we are using external authentication like Facebook, Twitter, Google, etc., then in those cases, we are not going to store the user password in the database. Now, if you go to the definition of the ExternalLoginConfirmation HTTP Post method of Account Controller, then you will see that it is calling the CreateAsync method with only the user object, as shown in the below code.
Here, you can also use Create method instead of the CreateAsync method as follows:
IdentityResult result = UserManager.Create(user);
UserManager (ApplicationUserManager) in ASP.NET Identity
We use the GetUserManager method to get the ApplicationUserManager from the OWIN context. If you go to the definition of the userManager property within the Account Controller, then you will see the following code. We have one private variable called _userManager and a public property called UserManager which is used to get and set the ApplicationUserManager object.
We use the ApplicationUserManager instead of the UserManager in order to use the default validation logic for usernames and passwords configured in the IdentityConfig.cs file. So, if you go to the IdentityConfig.cs file, then you will see that ApplicationUserManager is inherited from the UserManager class, as shown in the below image. The point that you need to remember is within the Create method of ApplicationUserManager class; it configures the validation logic for usernames and passwords.
Namespaces:
In order to use the GetUserManager method, the Create method, and the IdentityResult object, you have to include the following two namespaces:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
We have seen how the ASP.NET Identity uses the GetUserManager method, the Create method, and the IdentityResult object to create a new user.
Now, let us see how we can implement the Create user method manually, which is going to register a user into the database. First, create a class file with the name RegisterUserViewModel.cs within the Models folder and then copy and paste the following code into it.
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace AspNetIdentityWithNewProject.Models { public class RegisterUserViewModel { [Display(Name = "Username")] [Required] public string UserName { get; set; } [Display(Name = "First name")] public string FirstName { get; set; } [Display(Name = "Last name")] public string LastName { get; set; } [Display(Name = "Email")] [Required] [EmailAddress] public string Email { get; set; } [Display(Name = "Phone number")] [Phone] public string PhoneNumber { 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; } } }
Once you created the RegisterUserViewModel, then modify the HomeController as shown below.
using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using AspNetIdentityWithNewProject.Models; using System.Threading.Tasks; namespace AspNetIdentityWithNewProject.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } // // GET: /Home/AddUser [AllowAnonymous] public ActionResult AddUser() { return View(); } [HttpPost] public async Task<ActionResult> AddUser(RegisterUserViewModel model) { if (ModelState.IsValid) { ApplicationUser user = new ApplicationUser { FirstName = model.FirstName, LastName = model.LastName, PhoneNumber = model.PhoneNumber, Email = model.Email, UserName = model.UserName }; ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); IdentityResult result = await UserManager.CreateAsync(user, model.Password); // IdentityResult result = UserManager.Create(user, model.Password); if (result.Succeeded) { var SignInManager = HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToAction("Index", "Home"); } //Get the ID of the newly created user //if (result.Succeeded) //{ // string UserId = user.Id; // return RedirectToAction("Index", "Home", new { Id = UserId }); //} foreach (string error in result.Errors) ModelState.AddModelError("", error); } return View(model); } } }
This example shows how to create a new user through an HTTP Post request. Firstly, we gather the user information and retrieve the user manager from the OWIN context using the GetUserManager method. Then, we create the new user using the CreateAsync method. To confirm the operation’s success, we check the Succeeded property of the IdentityResult object. If it is unsuccessful, we utilize the AddModelError method to add the errors to the ModelState by looping through the list of Errors. The base constructor generates and populates the Id field when a new ApplicationUser object is instantiated. After ensuring the user was created successfully, we can safely access their Id.
Note: When using the SignInManager.SignInAsync method in an ASP.NET Identity and OWIN Cookie Authentication system, a ClaimsIdentity needs to be generated for the user. This ClaimsIdentity contains information about the user’s claims, including their assigned roles.
Creating AddUser.cshtml view:
Now, create the AddUser.cshtml view within the Home folder, which is present inside the Views folder. Once you create the AddUser.cshtml view, then copy and paste the following code into it.
@model AspNetIdentityWithNewProject.Models.RegisterUserViewModel @{ ViewBag.Title = "Register"; } <h2>@ViewBag.Title.</h2> @using (Html.BeginForm("AddUser", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() <h4>Create a new account.</h4> <hr /> @Html.ValidationSummary("", new { @class = "text-danger" }) <div class="form-group"> @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.FirstName, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.LastName, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.Password, new { @class = "form-control" }) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" }) <div class="col-md-10"> @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-default" value="Register" /> </div> </div> } @section Scripts { @Scripts.Render("~/bundles/jqueryval") }
Modifying _LoginPartial.cshtml view:
Next, modify the _LoginPartial.cshtml view as shown below. Here, we have modified the Register link to point out the Home Controller AddUser action method instead of the Register action method of the Account Controller.
@using Microsoft.AspNet.Identity @if (Request.IsAuthenticated) { using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" })) { @Html.AntiForgeryToken() <ul class="nav navbar-nav navbar-right"> <li> @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" }) </li> <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li> </ul> } } else { <ul class="nav navbar-nav navbar-right"> <li>@Html.ActionLink("Register", "AddUser", "Home", routeValues: null, htmlAttributes: new { id = "registerLink" })</li> <li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li> </ul> }
With the above changes in place, now run the application and click on the Register link, and it will open the following user Register page. Fill out the form by providing the necessary details and then click on the Register button, as shown in the below image.
Now, if you go and check the database, then you will see the newly created user with all the above information. So, this is how you create a new user in ASP.NET Identity.
In the next article, I am going to discuss How to Update and Delete a User Account in ASP.NET Identity with Examples. Here, in this article, I try to explain Create a User Account using ASP.NET Identity. I hope you enjoy this Create a User Account in ASP.NET Identity article.