首页 > 解决方案 > 如何获取当前Windows登录用户全名而不是域名

问题描述

我想获取当前的 Windows 用户全名,而不是域名。我正在使用下面的代码来获取用户名,但它的名字是带有域名的。

字符串用户名 = Request.ServerVariables["AUTH_USER"];

字符串 a=System.Web.HttpContext.Current.User.Identity.Name;字符串用户名 = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

在上面的 3 个语句中,我越来越像 APAC\san123。但在这里我想要我的全名。这里我在 c# 中使用 mvc。

标签: c#asp.net-mvcwindows

解决方案


您可以从活动目录中获取用户全名(使用 System.DirectoryServices.AccountManagement):

PrincipalContext context = new PrincipalContext(ContextType.Domain,Environment.UserDomainName);
string loginName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
UserPrincipal user = UserPrincipal.FindByIdentity(context, loginName);
string userName = user.Name; //=user.GivenName + " " + user.Surname;

推荐阅读