User.Identity.Name is returning UserName instead of Name

那年仲夏 提交于 2020-01-04 05:45:36

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/44602626/user-identity-name-is-returning-username-instead-of-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!