代码之家  ›  专栏  ›  技术社区  ›  user3378165

获取user.identity的名字和姓氏

  •  0
  • user3378165  · 技术社区  · 6 年前

    我使用Windows身份验证设置了一个Intranet应用程序。 我需要在标题中显示用户名和用户的首字母,例如:

    欢迎史密斯 JS

    到目前为止我所做的:

    <div class="header__profile-name">Welcome <b>@User.Identity.Name.Split('\\')[1]</b></div>
    <div class="header__profile-img">@User.Identity.Name.Split('\\')[1].Substring(0, 2)</div>
    

    问题是用户名不是 总是 名字的第一个字母+姓氏,有时用户名可以是名字+姓氏的第一个字母,例如:

    John Smith-用户名 可以 名缩写和姓 但有时也可以 铍: 约翰斯

    在这种情况下,我的代码是错误的,因为它将导致:

    而不是 JS

    如何获得完整的用户名:名和姓 User.identity ?

    然后,我将把我的代码建立在完整的用户名(名字和姓氏)上,以便设置首字母,而不是建立在不总是一致的用户名上。

    1 回复  |  直到 6 年前
        1
  •  4
  •   Hossein    6 年前

    在applicationuser类中,您会注意到一条注释(如果使用标准的MVC5模板),上面写着“在这里添加自定义用户声明”。

    考虑到这一点,下面是添加全名的过程:

    public class ApplicationUser : IdentityUser
    {
        public string FullName { get; set; }
    
        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
            userIdentity.AddClaim(new Claim("FullName", this.FullName));
            return userIdentity;
        }
    }
    

    这样,当有人登录时,全名声明将被放入cookie中。您可以让助手这样访问它:

    public static string GetFullName(this System.Security.Principal.IPrincipal usr)
    {
        var fullNameClaim = ((ClaimsIdentity)usr.Identity).FindFirst("FullName");
        if (fullNameClaim != null)
            return fullNameClaim.Value;
    
        return "";
    }
    

    更新

    您可以在创建用户时将其添加到用户的声明中,然后将其作为声明从用户检索。标识:

    await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));
    

    翻新:

    ((ClaimsIdentity)User.Identity).FindFirst("FullName")
    

    或者您可以直接从user.fullname获取用户并访问它:

    var user = await userManager.FindById(User.Identity.GetUserId())
    return user.FullName
    

    更新

    对于 intranet 你可以这样做:

    using (var context = new PrincipalContext(ContextType.Domain))
    {
        var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
        var firstName = principal.GivenName;
        var lastName = principal.Surname;
    }
    

    您需要添加对 System.DirectoryServices.AccountManagement 装配。

    您可以添加类似这样的剃刀助手:

    @helper AccountName()
        {
            using (var context = new PrincipalContext(ContextType.Domain))
        {
            var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
            @principal.GivenName @principal.Surname
        }
    }
    

    如果您从视图而不是控制器执行此操作,则还需要向web.config添加程序集引用:

    <add assembly="System.DirectoryServices.AccountManagement" />
    

    添加下 configuration/system.web/assemblies .