2014-09-03 297 views
9

我已将名和姓添加到ApplicationUser类。MVC User.Identity.Name,姓氏和名字

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

我的应用程序成功创建第一次和LastName表中,但我无法获得姓和名作为对_LoginPartial“User.Identity.Name”

显示

回答

10

在partialview _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 - 属性

更换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> 
+0

nope !,不给我“GetName” – Emil 2014-09-03 12:53:01

+0

是正确的名字和姓氏? – 2014-09-03 13:01:59

+0

是的,但是“User.Identity”似乎没有这些信息 – Emil 2014-09-03 13:12:18

3

你”当用户登录时,需要在用户名称中添加姓名。然后在您的视图中访问这些来自的声明。看看几乎相同的my answer here,只需要添加名称而不是主题。