【问题标题】:How to get all user from LDAP in C# Using DirectoryEntry() or PrincipalContext()?如何使用 DirectoryEntry() 或 PrincipalContext() 在 C# 中从 LDAP 获取所有用户?
【发布时间】:2021-12-02 10:37:18
【问题描述】:
private void ADQuery()
{
    try
    {
        string connString = "LDAP://10.0.10.11/dc=abcd,dc=ac,dc=in";//demo url

        string username = "cn=admin,dc=abcd,dc=ac,dc=in";
        string name = "cn=admin,dc=abcd,dc=ac,dc=in";
        string password = "secrate";

        string name2 = "10.0.10.11\admin";//  domain\username
            
        DirectoryEntry de = new DirectoryEntry(connString, name2, "secrate", AuthenticationTypes.Secure);
          
        var search = new DirectorySearcher(de)
                         {   
                             Filter = "(&(ou=employee)(objectClass=inetOrgPerson))"
                         };
        search.SearchScope = SearchScope.Subtree;

        // error thrown by this statement
        SearchResult results = search.FindOne();

        if (results != null)
        {
            string email = results.Properties["mail"].ToString();
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

我收到此错误:

“/”应用程序中的服务器错误。

发生了本地错误。

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详情:

System.DirectoryServices.DirectoryServicesCOMException:发生本地错误

【问题讨论】:

    标签: c# asp.net active-directory ldap


    【解决方案1】:

    查看您的代码,唯一让我印象深刻的问题是您的过滤器:

    Filter = "(&(ou=employee)(objectClass=inetOrgPerson))"
    

    在 Active Directory 中,inetOrgPerson 类不用于用户。如果您想查找用户对象,您应该使用它作为过滤器:

    Filter = "(&(objectClass=user)(objectCategory=person))"
    

    您也无法像您尝试的那样过滤ou。要将搜索限制在特定的 OU,请在您用于 SearchRootDirectoryEntry 对象的 LDAP 字符串中使用该 OU。在您的情况下,这是您的 connString 变量:

    string connString = "LDAP://10.0.10.11/OU=employee,dc=abcd,dc=ac,dc=in";
    

    另外,AuthenticationTypes.Secure 是默认的AuthenticationType,所以你不需要在构造函数中指定它:

    DirectoryEntry de = new DirectoryEntry(connString, name2, "secrate", AuthenticationTypes.Secure);
    

    同样,Subtree 是默认的SearchScope,所以你不需要这一行:

    search.SearchScope = SearchScope.Subtree;
    

    【讨论】:

    • 我已经按照你说的实现了,但仍然遇到同样的异常
    • System.DirectoryServices.DirectoryServicesCOMException:发生本地错误。我认为我在这里传递的用户名有问题吗? [域\用户]
    • 您的代码显示您使用 IP 地址作为域名:10.0.10.11\admin。那是行不通的。但是,如果用户在您连接的同一个域中,则根本不需要包含该域。只需使用用户名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 2021-09-14
    相关资源
    最近更新 更多