How to change Identity/Register Model

Coreysan 1,651 Reputation points
2023-05-01T16:03:17.5966667+00:00

I'm learning how to enhance the Identity suite of razor pages. For the Register model, I'd like to change the 1 property "Name" to 2 properties, "First Name" and "Last Name".

I'm not sure how to break apart the Name property and store it that way in the AspNetUsers table. Is there a simple way to do this (change a model somewhere and rebuild the table), or use inheritance?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

Accepted answer
  1. Zhi Lv - MSFT 32,106 Reputation points Microsoft Vendor
    2023-05-02T02:32:26.4366667+00:00

    Hi @Coreysan

    how to enhance the Identity suite of razor pages. For the Register model, I'd like to change the 1 property "Name" to 2 properties, "First Name" and "Last Name".

    You can flow the following steps to set the FirstName an LastName properties.

    1.Add the FirstName and LastName to the AspNetUsers table.

    create a ApplicationUser class and inherit theIdentityUser.

        public class ApplicationUser: IdentityUser
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    

    Then in the DbContext class, add the DbSet.

        public class ApplicationDbContext : IdentityDbContext
        {
    
            public DbSet<ApplicationUser> ApplicationUsers { get; set; }
     
            //public DbSet<Customer> Customers { get; set; }
            //public DbSet<Professional> Professionals { get; set; }
            //public DbSet<Account> Accounts { get; set; }
    
            protected override void OnModelCreating(ModelBuilder builder)
            {
                base.OnModelCreating(builder);  
                //builder.Entity<Account>(entity => { entity.ToTable("Accounts"); });
                //builder.Entity<Customer>(entity => { entity.ToTable("Customers"); });
                //builder.Entity<Professional>(entity => { entity.ToTable("Professionals"); });
            }
            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options)
            { 
            }
        }
    

    In the Program.cs file, change the Identity configuration to use ApplicationUser, instead of IdentityUser.

    builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    Then, in the _LoginPartial.cshtml page, change the injected manager reference to use the ApplicationUser.

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

    After that enable migration (use add-migration xxx and update-database commands) to generate the database.

    Check the database via SSMS, we can see the AspNetUsers table already has the FirstName and LastName columns:

    User's image

    2. Change the Register Model and Register view.

    Use Scaffold Identity to generate the identity pages: Right-click on the project > Add > New Scaffolded Item. From the left pane of the Add New Scaffolded Item dialog, select Identity > Add. In the Add Identity dialog, select the options you want. Select Add.

    In the Identity pages, by default these pages will use the IdentityUser, you need to change it to ApplicationUser. For example, change the Register page code as below:

    User's image

    [Note] In the Areas folder, we need to replace all the "IdentityUser" to the "ApplicationUser", because in the Program.cs file, we configured the identity to use ApplicationUser. So, we'd better to check each file one by one.

    In the Register.cshtml.cs page, add the FirstName and LastName properties:

            public class InputModel
            {
                /// <summary>
                ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
                ///     directly from your code. This API may change or be removed in future releases.
                /// </summary>
                [Required]
                [EmailAddress]
                [Display(Name = "Email")]
                public string Email { get; set; }
    
                /// <summary>
                ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
                ///     directly from your code. This API may change or be removed in future releases.
                /// </summary>
                [Required]
                [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
                [DataType(DataType.Password)]
                [Display(Name = "Password")]
                public string Password { get; set; }
    
                /// <summary>
                ///     This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used
                ///     directly from your code. This API may change or be removed in future releases.
                /// </summary>
                [DataType(DataType.Password)]
                [Display(Name = "Confirm password")]
                [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
                public string ConfirmPassword { get; set; }
    
    
                public string FirstName { get; set; }
    
                public string LastName { get; set; }
            }
    
    

    And in the OnPostAsync method, when create the new user, remember to set the FirstName and LastName value.

            public async Task<IActionResult> OnPostAsync(string returnUrl = null)
            {
                returnUrl ??= Url.Content("~/");
                ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                if (ModelState.IsValid)
                {
                    var user = CreateUser();
                    user.FirstName = Input.FirstName;
                    user.LastName = Input.LastName;
    
                    await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
                    await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);
                    var result = await _userManager.CreateAsync(user, Input.Password);
    
    

    Then in the Register.cshtml page, add the following html elements in the form:

    @page
    @model RegisterModel
    @{
        ViewData["Title"] = "Register";
    }
    
    <h1>@ViewData["Title"]</h1>
    
    <div class="row">
        <div class="col-md-4">
            <form id="registerForm" asp-route-returnUrl="@Model.ReturnUrl" method="post">
                <h2>Create a new account.</h2>
                <hr />
                <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
                    <label asp-for="Input.Email">Email</label>
                    <span asp-validation-for="Input.Email" class="text-danger"></span>
                </div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.FirstName" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
                    <label asp-for="Input.FirstName">FirstName</label>
                    <span asp-validation-for="Input.FirstName" class="text-danger"></span>
                </div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.LastName" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" />
                    <label asp-for="Input.LastName">LastName</label>
                    <span asp-validation-for="Input.LastName" class="text-danger"></span>
                </div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.Password" class="form-control" autocomplete="new-password" aria-required="true" placeholder="password" />
                    <label asp-for="Input.Password">Password</label>
                    <span asp-validation-for="Input.Password" class="text-danger"></span>
                </div>
                <div class="form-floating mb-3">
                    <input asp-for="Input.ConfirmPassword" class="form-control" autocomplete="new-password" aria-required="true" placeholder="password" />
                    <label asp-for="Input.ConfirmPassword">Confirm Password</label>
                    <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span>
                </div>
                <button id="registerSubmit" type="submit" class="w-100 btn btn-lg btn-primary">Register</button>
            </form>
        </div>
    

    After running, the register page as below:

    User's image

    Checking the database, the result as below:

    User's image

    3.To display the FirstName and Last Name after login.

    In the _LoginPartial.cshtml page, get the current user via UserManager, then get the FirstName and LastName:

    @using Microsoft.AspNetCore.Identity
    @using WebApplication7.Data
    @inject SignInManager<ApplicationUser> SignInManager
    @inject UserManager<ApplicationUser> UserManager
    
    <ul class="navbar-nav">
    @if (SignInManager.IsSignedIn(User))
    {
        
        <li class="nav-item">
            @{
                    var currentuser = await UserManager.GetUserAsync(User);
            }
            <a  class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @currentuser.FirstName @currentuser.LastName!</a>
        </li>
    

    The result as below:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    6 people found this answer helpful.

0 additional answers

Sort by: Most helpful