c# - 获取 User.identity 的名字和姓氏

标签 c# asp.net-mvc

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

Welcome 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>

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

John Smith - the username can be jsmith but sometimes it can also be: johns

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

jo instead of 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
    }
}

如果您打算从 View 而不是 Controller 执行此操作,则还需要将程序集引用添加到您的 web.config:

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

configuration/system.web/assemblies 下添加。

关于c# - 获取 User.identity 的名字和姓氏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51943909/

相关文章:

c# - 根据另一个 ListView 中的选择更改 ListView 中的选定项目

c# - 用c#实现水平滚动

c# - MVC 5 未正确验证 StringLength 属性

asp.net-mvc - Mvc flash 消息作为局部 View

c# - 使用 JsonResult 显示验证消息

c# - 在通过 Unity 解析派生类时在基类中隐式注入(inject)依赖项

c# - UWP 中的 httpclient 问题

c# - 如何为服务器端 Blazor 应用程序生成 xml 站点地图

javascript - 将类添加到 ValidationSummary

asp.net-mvc - 如何覆盖 HTML 帮助器方法用于模型属性的字符串表示形式?