繁体   English   中英

如何从Windows身份验证获取名字和姓氏

[英]how to get first and last name from windows authentification

我是asp.net mvc的新手,需要在_Layout视图中显示用户的名字和姓氏。

我的用户名没有通过此行的域名数据

@Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(@"\") + 1)

我看到了一个看起来像的解决方案-

添加引用System.DirectoryServices.AccountManagement

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

像这样添加一个Razor助手:

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

但是没有用于_Layout.cshtml的控制器,如果我直接将其放在剃须刀中,它也不起作用。

任何帮助将被申请!

好的,所以在考虑了Razor的工作原理后,我在_Layout.cshtml中找到了解决方案-

<head>
    @using System.DirectoryServices.AccountManagement;
</head>

<body>
    @{
        var context = new PrincipalContext(ContextType.Domain);
        var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
        var firstName = principal.GivenName;
        var lastName = principal.Surname;
    }
<p class="navbar-brand"> @firstName @lastName </p>
</body>

希望对您有所帮助。

暂无
暂无

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

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