我有一个MVC 3内部网应用程序,可以针对特定域执行Windows身份验证。我想渲染当前用户的名字。
在视图中,
@User.Identity.Name
设置为DOMAIN\Username
,我想要的是他们的完整Firstname Lastname
答案 0 :(得分:56)
您可以这样做:
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
}
}
如果您从视图而不是控制器中执行此操作,则还需要向web.config添加程序集引用:
<add assembly="System.DirectoryServices.AccountManagement" />
在configuration/system.web/assemblies
下添加。
答案 1 :(得分:7)
另一个选项,无需帮助程序......您可以在需要使用这些值之前声明上下文和主体,然后像标准输出一样使用它......
@{ // anywhere before needed in cshtml file or view
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
}
然后在文档中的任何位置,只需根据需要调用每个变量:
@principal.GivenName // first name
@principal.Surname // last name
答案 2 :(得分:2)
如果你有很多控制器,那么使用@vcsjones方法可能会很痛苦。 因此,我建议为TIdentity创建扩展方法。
public static string GetFullName(this IIdentity id)
{
if (id == null) return null;
using (var context = new PrincipalContext(ContextType.Domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(context, id.Name);
return userPrincipal != null ? $"{userPrincipal.GivenName} {userPrincipal.Surname}" : null;
}
}
然后你可以在你的视图中使用它:
<p>Hello, @User.Identity.GetFullName()!</p>
答案 3 :(得分:1)
如果您已升级到身份2并正在使用声明,则此类信息将成为声明。尝试创建扩展方法:
public static string GetFullName(this IIdentity id)
{
var claimsIdentity = id as ClaimsIdentity;
return claimsIdentity == null
? id.Name
: string.Format("{0} {1}",
claimsIdentity.FindFirst(ClaimTypes.GivenName).Value,
claimsIdentity.FindFirst(ClaimTypes.Surname).Value);
}
然后你可以在这样的视图中使用它:
@Html.ActionLink("Hello " + User.Identity.GetFullName() + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
答案 4 :(得分:0)
在您的 _ViewImports.cshtml 页面中添加以下内容:
@using System.DirectoryServices.AccountManagement
然后,在您的 _Layouts.cshtml 中放置以下内容:
@{
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);}
注意:您可以通过创建附加变量来进行连接,例如:
var userName = @principal.Givenname + ", " + @principal.Surname;
您不能直接调用变量“userName”,但是,您可以通过创建隐藏字段在页面上的任何位置调用“userName”。