获取 User.identity 的名字和姓氏

use*_*165 3 c# asp.net-mvc

我有一个使用 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>
Run Code Online (Sandbox Code Playgroud)

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

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

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

jo而不是js

我怎样才能获得完整的用户名:名字和姓氏User.identity

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

Hos*_*ein 7

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

使用此功能,当有人登录时,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 "";
}
Run Code Online (Sandbox Code Playgroud)

更新

或者,您可以在创建用户时将其添加到用户的声明中,然后将其作为来自 User.Identity 的声明进行检索:

await userManager.AddClaimAsync(user.Id, new Claim("FullName", user.FullName));
Run Code Online (Sandbox Code Playgroud)

检索它:

((ClaimsIdentity)User.Identity).FindFirst("FullName")
Run Code Online (Sandbox Code Playgroud)

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

var user = await userManager.FindById(User.Identity.GetUserId())
return user.FullName
Run Code Online (Sandbox Code Playgroud)

更新

因为intranet你可以做这样的事情:

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

您需要添加对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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<add assembly="System.DirectoryServices.AccountManagement" />
Run Code Online (Sandbox Code Playgroud)

configuration/system.web/assemblies.