Add Custom User Data To Identity Core Register Form In ASP.NET Core 3.0

Managing Users with UserManager and SignInManager

Today in this article I will explain how to add custom user data in your registration form with the help of Identity Core in ASP.NET Core. This article is a continuation of previous articles. Those article links are given below.

Here is the complete code,

Step 1. Start-up Visual Studio 2019. Now click on Create New Project and Choose ASP.NET Core Web Application and click on “Next

After clicking next, another wizard will open. Under the project name, give a meaningful name to your project, and click on Create.

That will open up another new wizard; select ASP.Net Core 3.0 from the dropdown. If not, select default. Choose the Web Application (Model-View-Controller) template and click on Create which will create your first ASP.Net Core Application.

Step 2. Now under the Models folder create the class ApplicationUser. This class will inherit from the IdentityUser class. Now define the fields that you want to “Add” in your registration form.

using Microsoft.AspNetCore.Identity;

namespace CustomUserData_Demo.Models
{
    public class ApplicationUser : IdentityUser
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

Step 3.Now open the ApplicationDbContext.cs class which is located under the Data folder. Modify the class as below.

using CustomUserData_Demo.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace CustomUserData_Demo.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
}

Step 4.Now open startup.cs class and “Add” the following code or configure ApplicationUser class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>(options =>
        options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddControllersWithViews();
    services.AddRazorPages();
}

Step 5. Now create a folder called ViewModel and “Add” a class with the name RegisterViewModel. We will use this as a model for registering.

using System.ComponentModel.DataAnnotations;

namespace CustomUserData_Demo.ViewModel
{
    public class RegisterViewModel
    {
        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [Phone]
        [Display(Name ="Phone Number")]
        public string PhoneNumber { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Required]
        [Display(Name = "Confirm Password")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Your password and confirm password do not match")]
        public string ConfirmPassword { get; set; }
    }
}

Step 6. Now under the project, create a folder with the name Controllers. After creating the “Controllers” folder, right-click on the “Controllers” folder and add a controller.

A window will appear. Choose MVC Controller-Empty and click "Add".

After clicking on "Add", another window will appear with DefaultController. Change the name to AccountController and click on "Add". The AccountController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Account.

Step 7. Now “Add” IActionResult method with the name Register. Write the following below code to register the user.

using System.Threading.Tasks;
using CustomUserData_Demo.Models;
using CustomUserData_Demo.ViewModel;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace CustomUserData_Demo.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> userManager;
        private readonly SignInManager<ApplicationUser> signInManager;
        
        public AccountController(UserManager<ApplicationUser> userManager,
                                  SignInManager<ApplicationUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }
        
        public IActionResult Register()
        {
            return View();
        }
        
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    PhoneNumber = model.PhoneNumber,
                    UserName = model.Email,
                    Email = model.Email,
                };
                
                var result = await userManager.CreateAsync(user, model.Password);
                
                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
            
            return View();
        }
    }
}

Step 8. Now right-click on the register action method and “Add View” with the default name Register to click on “Add”. It will be added under the views folder; account folder with Register.cshtml.

@model CustomUserData_Demo.ViewModel.RegisterViewModel

@{
    ViewData["Title"] = "Register";
}

<p class="row">
    <p class="col-md-8 mx-auto">
        <p class="card">
            <p class="card-header bg-primary text-white">
                <h5 class="text-uppercase text-center">User Registration Form</h5>
            </p>
            <p class="card-body">
                <form asp-action="Register">
                    <p class="row">
                        <p class="col-md-6">
                            <p class="form-group">
                                <label asp-for="FirstName"></label>
                                <input asp-for="FirstName" class="form-control" />
                                <span asp-validation-for="FirstName" class="text-danger"></span>
                            </p>
                        </p>
                        <p class="col-md-6">
                            <p class="form-group">
                                <label asp-for="LastName"></label>
                                <input asp-for="LastName" class="form-control" />
                                <span asp-validation-for="LastName" class="text-danger"></span>
                            </p>
                        </p>
                    </p>
                    <p class="row">
                        <p class="col-md-6">
                            <p class="form-group">
                                <label asp-for="PhoneNumber"></label>
                                <input asp-for="PhoneNumber" class="form-control" />
                                <span asp-validation-for="PhoneNumber" class="text-danger"></span>
                            </p>
                        </p>
                        <p class="col-md-6">
                            <p class="form-group">
                                <label asp-for="Email"></label>
                                <input asp-for="Email" class="form-control" />
                                <span asp-validation-for="Email" class="text-danger"></span>
                            </p>
                        </p>
                    </p>
                    <p class="row">
                        <p class="col-md-6">
                            <p class="form-group">
                                <label asp-for="Password"></label>
                                <input asp-for="Password" class="form-control" />
                                <span asp-validation-for="Password" class="text-danger"></span>
                            </p>
                        </p>
                        <p class="col-md-6">
                            <p class="form-group">
                                <label asp-for="ConfirmPassword"></label>
                                <input asp-for="ConfirmPassword" class="form-control" />
                                <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
                            </p>
                        </p>
                    </p>
                    <input type="submit" value="Register" class="btn btn-sm btn-primary text-uppercase rounded-0" />
                </form>
            </p>
        </p>
    </p>
</p>

Step 9. Now under the views folder find the shared folder open _LoginPartial.cshtml and modify it as below.

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

<ul class="navbar-nav">
    @if (SignInManager.IsSignedIn(User))
    {

    }
    else
    {
        <li class="nav-item">
            <a class="nav-link" asp-controller="Account" asp-action="Register">Register</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-controller="Account" asp-action="Login">Login</a>
        </li>
    }
</ul>

Step 10. Now press ctrl+F5 and run your project.

 Run your project