繁体   English   中英

获取用户名和姓氏

[英]Get first name and last name of User.identity

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

欢迎jSmith 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>

问题在于用户名并不总是姓和名的首字母,有时用户名可以是ex的名字和名的首字母:

John Smith-用户名可以jsmith,但有时也可以是: johns

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

用jo代替js

如何获取完整的用户名:带有User.identity名字和User.identity

然后,我将基于完整的用户名(名字和姓氏)创建代码,以设置缩写名,而不是基于并非始终一致的用户名。

在ApplicationUser类中,您会注意到一条注释(如果使用标准MVC5模板),该注释为“在此处添加自定义用户声明”。

鉴于此,添加FullName如下所示:

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

使用此方法,当有人登录时,会将FullName声明放入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 "";
}

更新

或者您可以在创建用户时将其添加到用户的声明中,然后从User.Identity中检索它作为声明。

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程序集的引用。

您可以像这样添加Razor助手:

@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下添加它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM