Display users full name instead of email in ASP.NET Core

In ASP.NET core by default logged in user’s email is shown in header after login.

We can show any other information like First or Last Name or even full name (by combining these two).

To achieve this we need to make the following changes:

Customize your Identity User

Customize the identity user and identity role (if needed) as shown below:

 public class ApplicationUser: IdentityUser<int>
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
public class ApplicationRole : IdentityRole<int>
    {
        //add fields here
    }
Apply the database migration.
Configure it in ConfigureServices method of Startup class as shown below:
 services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

Customize UserClaimsPrincipalFactory class

public class CustomUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser,ApplicationRole>
    {
        public CustomUserClaimsPrincipalFactory(
            UserManager<ApplicationUser> userManager,
            RoleManager<ApplicationRole> roleManager,
            IOptions<IdentityOptions> optionsAccessor)
            : base(userManager,roleManager, optionsAccessor)
        {
        }

        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(ApplicationUser user)
        {
            var identity = await base.GenerateClaimsAsync(user);
            identity.AddClaim(new Claim(ClaimTypes.GivenName, user.FirstName + " " + user.LastName ?? ""));
            return identity;
        }

        
    }

Configure ClaimsPrincipalFactory in Startup

Configure it in ConfigureServices method of Startup class, so final identity configuration will look like as shown below:

            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders()                .AddClaimsPrincipalFactory<CustomUserClaimsPrincipalFactory>();

Make changes in _LoginPartial.cshtml view

Change the code to show the logged in user’s full name instead of email, please see the example below:

<a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @(User.FindFirst(System.Security.Claims.ClaimTypes.GivenName)?.Value)!</a>

Hopefully it will help you fix a common issue in latest ASP.NET Core (3.1) applications.

Comments
Share it