Add Individual User Account and User Name in MVC Core project

Here details the steps to add the "Individual User Account" feature and to customize registration page to add "User Name".

When you create a MVC Core web application, if you select MVC template, it will let you choose "Individual User Accounts" Authentication. This will generate default pages for account registration, management and login pages.

Run the project generated, and try the login function you'll get an error page, since login tables needs to be manually created.

In Visual Studio, select Tools->Nuget Console->Select "Default Project"-> Run the following 2 commands to create identity tables:

Add-Migration Initial

Visual Studio created an account registration page with Email and Password. Try create an user and login. Your email address will shows on the top-right corner. This is a problem. If a user logs in to your website and writes a post, he probably won't won't to expose his email on the post. You should ask the user to enter and display the user name instead.

The table that saves user accounts is AspNetUsers table. If you check that table, the UserName column already exists. But you won't be able to find account registration page for you to add UserName. By default, Visual Studio won't generate user management pages in the MVC projects.

Here're the steps to add "User Name" to account registration page:

  1. Right click your project -> select "Add" -> select "Add New Scaffolded Item" -> select "Identity" on the left -> Click "Add" -> Check "Account\Register" -> select "Data context class" -> click "Add"

  2. After the last step, an "Area" folder will be created under your project. You can find 2 files inside this folder:

    Register.cshtml, Register.cshtml.cs

  3. Open Register.cshtml.cs file, find InputModel class, add UserName property to the class and mark it as required

    [Display(Name = User Name)]
    [StringLength(20, ErrorMessage = The {0} must be at least {2} and at max {1} characters long., MinimumLength = 6)]
    public string UserName { get; set; }

  4. In Register.cshtml.cs file, inside OnPostAsync method, Assign UserName to Input.UserName from Input.Email

    var user = new IdentityUser { UserName = Input.UserName, Email = Input.Email };

  5. Open Register.cshtml, add User Name section under Email section,

    <div class=form-group>
        <label asp-for="Input.UserName"></label>
        <input asp-for="Input.UserName" class="form-control" />
        <span asp-validation-for="Input.UserName class="text-danger"></span>

  6. Run the project. Register a new account, you'll see "User Name" input control is added. After account registration is submitted, you'll see the user name instead of email will show on the top-right corner instead of email address. Check user account management page, user name will also be displayed.