MVC User.Identity.Name with first and last names

試著忘記壹切 提交于 2019-12-10 02:21:35

问题


I have added First and Last name to the ApplicationUser Class.

 public class ApplicationUser : IdentityUser
    {
        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
            return userIdentity;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

also added information to RegisterViewModel

My application successfully created First and LastName to the table but I am unable to get the first and last names as to display in _LoginPartial "User.Identity.Name"


回答1:


in your partialview _LoginPartial.cshtml

Add the code:

@if (Request.IsAuthenticated)
{
    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
    var user = manager.FindById(User.Identity.GetUserId());
...
}

ApplicationDbContext = your DBContext -> Default : ApplicationDbContext

With the instance of ApplicationUser (user) you can get First- and LastName-property

Replace User.Identity.Name with user.FirstName + " " + user.LastName like this:

<ul class="nav navbar-nav navbar-right">
    <li>
        @Html.ActionLink("Hello " + user.FirstName + " " + user.LastName + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
    </li>
    <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>



回答2:


You'll need to add names as a Claim on user when user is logged in. Then in your views access these claims from ClaimsPrincipal.Current.Claims. Have a look on my answer here that does pretty much the same, only you need to add names instead of theme.



来源:https://stackoverflow.com/questions/25643251/mvc-user-identity-name-with-first-and-last-names

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