【问题标题】:Get Name of User from Active Directory从 Active Directory 获取用户名
【发布时间】:2016-08-29 20:55:24
【问题描述】:

我只需要显示 Active Directory 中的用户名,我正在使用

 lbl_Login.Text = User.Identity.Name; //the result is domain\username

这显示的是用户名而不是用户的真实姓名,我已经检查了这里相关的其他问题和答案,但我没有得到解决方案。

是否有像“User.Identity.Name”这样的属性来仅获取用户的名称?

【问题讨论】:

  • 我将发布一个获取完整显示名称的简单方法

标签: c# asp.net active-directory


【解决方案1】:

您需要活动目录中的用户名。试试这样的代码:

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 namespace 提供跨多个主体存储的用户、计算机和组安全主体的统一访问和操作:Active Directory 域服务 (AD DS)、Active Directory 轻型目录服务 (AD LDS) 和计算机 SAM ( MSAM)。

【讨论】:

  • 不正确@MethodMan,肯定 Response.Write 或 Debug.Write 更常见,但您仍然可以使用控制台输出。
  • System.DirectoryServices.AccountManagement 比 DirectoryEntry 慢?
  • @Kiquenet 我无法回答你的问题,因为我没有检查它。
  • @DenisBubnov 使用相同的代码。我怎样才能获取该用户的电话号码。?现在我通过使用此代码获取电子邮件 ID (email= usr.EmailAddress;)
  • “用户”来自哪个命名空间?
【解决方案2】:
using 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;
        }
    }
}

【讨论】:

  • 谢谢,这也有效,我只需将替换“User.Identity.Name”添加到您手动放置我的用户名的位置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 2018-09-21
  • 1970-01-01
相关资源
最近更新 更多