我是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没有控制器,如果我把它直接放在剃须刀中,它也不起作用。
任何帮助都会得到满足!!
答案 0 :(得分:1)
<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>
希望它会有所帮助。