【问题标题】:how to get first and last name from windows authentification如何从 Windows 身份验证中获取名字和姓氏
【发布时间】:2017-07-11 07:28:52
【问题描述】:

我是 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 没有控制器,如果我将它直接放在剃须刀中,它也不起作用。

如有任何帮助,将不胜感激!

【问题讨论】:

  • 怎么用会话...
  • 但是逻辑在哪里?我需要在 _Layout.cshtml 中显示它。我如何从会话中获取名字和姓氏?据我所知,我可以获得密钥\用户名\计算机名...
  • 您可以在登录后将名字和姓氏存储在会话变量中。我的意思是在登录操作方法中。然后你就可以在你的 _Layout 页面中访问它们了。
  • 我没有登录操作方法,因为它是Intranet,所以我有自动登录的Windows身份验证
  • 然后你就可以在你的登陆/主页上写了。然后你可以在你的布局页面中检索。

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

好的,经过大量思考 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>

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多