【问题标题】:Querying Active Directory using C# for user email by employee ID通过员工 ID 使用 C# 查询 Active Directory 以获取用户电子邮件
【发布时间】:2018-11-16 19:25:02
【问题描述】:

是否可以使用employeenumber 作为查询词从Active Directory 获取用户的电子邮件?

我正在使用 C# 的 System.DirectoryServices 并且有点迷茫。我公司以前的开发人员正在使用此流程,但他有一封电子邮件并正在查询员工编号。我已经把它改成了我认为应该的样子,但老实说,我不太了解代码。

我的代码有问题吗?每次我运行它时,我都会在 DirectoryEntry up_user = 行上收到空引用错误。我认为这是因为上一行没有得到任何实体。

另外,关于这个主题有什么好的文档吗?我到处看,帖子都是 2011 年或 2013 年的。

我有以下几点:

try
{
    string email = string.Empty;
    ContextType authenticationType = ContextType.Domain;
    PrincipalContext principalContext = new PrincipalContext(authenticationType, "MATRIC");
    UserPrincipal userPrincipal = null;

    userPrincipal = UserPrincipal.FindByIdentity(principalContext, empnum);

    DirectoryEntry up_User = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
    DirectorySearcher deSearch = new DirectorySearcher(up_User);
    SearchResultCollection results = deSearch.FindAll();
    if (results != null && results.Count > 0)
    {
        ResultPropertyCollection rpc = results[0].Properties;
        foreach (string rp in rpc.PropertyNames)
        {
            if (rp == "mail") 
            {
                email = rpc["mail"][0].ToString();
            }
        }

        if (email != string.Empty)
        {
            return email;
        }

        return null;
    }
            return null;
}
catch (Exception ex)
{
    throw ex;
}

【问题讨论】:

标签: c# active-directory directoryservices


【解决方案1】:

UserPrincipal.FindByIdentity 仅适用于通过 AD 认为的识别属性来查找用户。这些在IdentityType 枚举中列出。员工编号不是其中之一。

您在 AD 中使用的是 employeeId 还是 employeeNumber?它们是不同的属性,虽然两者都只是在 AD 中没有特殊含义或限制的字符串。

employeeId 属性在UserPrincipal 类中公开,因此您可以使用UserPrincipal 进行搜索,如the answer here 中所述:

UserPrincipal searchTemplate = new UserPrincipal(principalContext);
searchTemplate.EmployeeID = employeeId;
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal)ps.FindOne();

然后您可以使用您找到的帐户的EmailAddress 属性(您无需执行您正在使用DirectorySearcher 执行的操作)。

var emailAddress user?.EmailAddress;

如果您使用的是employeeNumber,则需要使用DirectorySearcher 才能找到它。像这样的:

var search = new DirectorySearcher(new DirectoryEntry("LDAP://yourdomain.com"));
search.Filter = $"(&(ObjectClass=user)(employeeNumber={employeeNumber}))"; 
search.PropertiesToLoad.Add("mail");

var result = search.FindOne();
string emailAddress = null;
if (result.Properties.Contains("mail")) {
    emailAddress = result.Properties["mail"][0].Value as string;
}

【讨论】:

  • 我正在使用员工编号。所以在最后一段代码中,过滤器说 get users where employeeNumber = 我提供的 EmployeeNumber?然后它只加载mail。在结果中它找到了employeeNumber 的第一个匹配项并将emailAddress 设置为搜索结果?对不起,我只是想了解它
  • 对。因此,该代码假定您已经有一个名为 employeeNumber 的变量。然后它将emailAddress 设置为它找到的用户的mail 属性。
猜你喜欢
  • 2023-04-06
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
相关资源
最近更新 更多