【问题标题】:Extending an LDAP query with C#使用 C# 扩展 LDAP 查询
【发布时间】:2012-07-19 22:02:25
【问题描述】:

我目前有几种方法:

public ADHelper()
        {

           connection =  InitializeConnection();

        }

        private DirectoryEntry InitializeConnection()
        {
            DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://servername.domain.com:389/DC=domain,DC=com");
            ldapConnection.Username = "user"
            ldapConnection.Password = "password";

            ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
            return ldapConnection;

        }

我想创建另一种方法来检查该域中是否存在对象。我目前正在这样做:

public bool Exists(string objectPath)
        {
            bool found = DirectoryEntry.Exists("LDAP://" + objectPath);
            return found;
        }

但这迫使我指定整个 LDAP 字符串。我想简单地在 Exists() 方法中使用 OU 和 CN 参数扩展初始 ldapConnection 。有没有办法在不公开 Initialize() 方法的情况下实现这一点?

非常感谢!

【问题讨论】:

  • 如果您只需要基于CN 搜索DirectoryEntry,您可以使用DirectorySearcher 来完成。

标签: active-directory ldap active-directory-group


【解决方案1】:

可能是这样的:

public bool AccountExists(string userEmail)
{
    using (var root = GetLdapRoot())
    {
        using (var searcher = new DirectorySearcher(root))
        {
            searcher.Filter = string.Format("(&(objectClass=User)(mail={0}))", userEmail);
            searcher.PropertiesToLoad.Add("email");
            var result = searcher.FindAll();
            return result.Count > 0;
        }
    }
}


private static DirectoryEntry GetLdapRoot()
{
    return new DirectoryEntry("LDAP://DC=com"); //or whatever your root domain is. Set credentials if you need to
}

通过设置过滤器并具体说明要加载的属性,搜索将更加有效。通过使用根目录作为 LDAP:// 字符串,您应该搜索整个目录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多