Asp.net

帶有名字和姓氏的 MVC User.Identity.Name

  • June 5, 2015

我已將名字和姓氏添加到ApplicationUser班級。

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; }
   }

還添加了資訊RegisterViewModel

我的應用程序成功創建了 First 和LastNametable,但我無法獲取顯示在_LoginPartial “User.Identity.Name”中的名字和姓氏

在你的局部視圖中_LoginPartial.cshtml

添加程式碼:

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

ApplicationDbContext= 你的 DBContext -> 預設:ApplicationDbContext

使用您的實例ApplicationUser (user)可以獲得First-LastName-property

替換User.Identity.Nameuser.FirstName + " " + user.LastName這樣:

<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>

引用自:https://stackoverflow.com/questions/25643251