具有名字和姓氏的MVC User.Identity.Name [英] MVC User.Identity.Name with first and last names

查看:100
本文介绍了具有名字和姓氏的MVC User.Identity.Name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在ApplicationUser类中添加了名字和姓氏.

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

还向RegisterViewModel

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

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"

推荐答案

在您的局部视图_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

ApplicationDbContext = your DBContext -> Default : ApplicationDbContext

使用ApplicationUser (user)实例,您可以获得First-LastName-属性

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

User.Identity.Name替换为user.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>

这篇关于具有名字和姓氏的MVC User.Identity.Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆