具有名和姓的MVC User.Identity.Name

Emi*_*mil 9 asp.net razor asp.net-mvc-4 asp.net-identity

我已将ApplicationUserClass 和Last名称添加到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; }
    }
Run Code Online (Sandbox Code Playgroud)

还添加了信息 RegisterViewModel

我的应用程序成功创建了First和LastName表,但是我无法获得在_LoginPartial "User.Identity.Name"中显示的名字和姓氏

Edi*_* G. 10

在你的部分视图中 _LoginPartial.cshtml

添加代码:

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

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>
Run Code Online (Sandbox Code Playgroud)

  • 这很有效,值得注意的是我必须添加一些using语句来了解所有这些内容:使用Microsoft.AspNet.Identity.EntityFramework使用MyApp.Models (3认同)
  • @EdiG.是的,这会奏效.但请注意,在每次请求时,这都会导致对数据库的额外调用,这是可以避免的.如果我们在表中说1M用户,这个额外的调用将使应用程序停止. (2认同)