我需要从Active Directory中仅显示用户的名称,我正在使用
lbl_Login.Text = User.Identity.Name; //the result is domain\username
这显示了用户的名称,但不是用户的真实姓名,我查看了其他相关的问题和答案,但没有得到解决方案。
是否有类似于“User.Identity.Name”的属性仅获取用户的名称?
我需要从Active Directory中仅显示用户的名称,我正在使用
lbl_Login.Text = User.Identity.Name; //the result is domain\username
这显示了用户的名称,但不是用户的真实姓名,我查看了其他相关的问题和答案,但没有得到解决方案。
是否有类似于“User.Identity.Name”的属性仅获取用户的名称?
您想要从活动目录中获取用户的名称。可以尝试以下代码:
string name ="";
using (var context = new PrincipalContext(ContextType.Domain))
{
var usr = UserPrincipal.FindByIdentity(context, User.Identity.Name);
if (usr != null)
name = usr.DisplayName;
}
或者可以参考来自social.msdn.microsoft.com的内容:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.Current;
string displayName = user.DisplayName;
或者是这样:
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName;
System.DirectoryServices.AccountManagement命名空间提供了跨多个主要存储区域(Active Directory Domain Services(AD DS)、Active Directory Lightweight Directory Services(AD LDS)和Machine SAM(MSAM))对用户、计算机和组安全主体进行统一访问和操作的功能。
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
的目的是什么?看起来 ctx 在那里没有被使用。 - Doc Brownusing System.DirectoryServices.AccountManagement;
string fullName = null;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name))
{
if (user != null)
{
fullName = user.DisplayName;
lbl_Login.Text = fullName;
}
}
}