Search code examples
asp.net-mvcrazorviewasp.net-identity

User.Identity.Name is returning UserName instead of Name


I want to display Name of a user instead of UserName in navbar that is in _LoginPartial Currently I'm using User.Identity.GetUserName() for userName but now I want to display Name of the current user.

_LoginPartial is called by the Startup.Auth.cs so I can't run the query on the backend and get the Name of my user so I can only use built-in functions which can run by razor in view.

I have tried all of them but they all are giving me username instead of name of the user.

<small>@System.Threading.Thread.CurrentPrincipal.Identity.Name</small>
<small>@User.Identity.Name</small>
<small>@threadPrincipal.Identity.Name</small>
<small>@System.Web.HttpContext.Current.User.Identity.Name</small>

How can I get the name instead of userName

This is the User Table

ID
Email
EmailConfirm
Password
Security
PhoneNumber
PhoneNumberConfirm
TwoFactorEnable
LockoutEndDateUtc
LockoutEnable
AccessFailedCount
UserName
Name
Status
Image

Solution

  • Since Name is a custom field of ApplicationUser (the extended IdentityUser) you'll need to add the field as claim.

    If you've used the template to setup Identity then you'll find in IdentityModels.cs the class ApplicationUser. Here I've added a field 'Name' and added this as claim:

    public class ApplicationUser : IdentityUser
    {
        public string Name { get; set; }
    
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    
            // Add custom user claims here
            userIdentity.AddClaim(new Claim("CustomName", Name));
    
            return userIdentity;
        }
    }
    

    This code will add a claim 'CustomName' which has the value of the name.

    In your view you can now read the claims. Here's an example in _LoginPartial:

    <ul class="nav navbar-nav navbar-right">
        <li>
            @{ var user = (System.Security.Claims.ClaimsIdentity)User.Identity; }
            @Html.ActionLink("Hello " + user.FindFirstValue("CustomName") + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
    

    You can add other custom fields as well as claims.