如何从windows authentification

时间:2017-07-11 07:28:53

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

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

任何帮助都会得到满足!!

1 个答案:

答案 0 :(得分: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>

希望它会有所帮助。