获取用户名和姓氏

用户名

我有一个使用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

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

侯赛因

在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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章