【问题标题】:Limiting the attributes returned in an LDAP query限制 LDAP 查询中返回的属性
【发布时间】:2011-10-02 20:23:28
【问题描述】:

如何限制通过 System.DirectoryServices 在 LDAP 查询中返回的属性?

我一直在使用 DirectorySearcher 并将我想要的属性添加到 DirectorySearcher.PropertiesToLoad。问题是这只是确保添加的属性包含在 DirectoryEntry.Properties 以及一些默认列表中。有什么方法可以指定您想要返回的唯一属性吗?

DirectoryEntry base = new DiectoryEntry(rootPath, null, null, AuthenticationTypes.FastBind);
DirectorySearcher groupSearcher = new DirectorySearcher(base);
groupSearcher.Filter = "(objectClass=group)";
groupSearcher.PropertiesToLoad.Add("distinguishedName");
groupSearcher.PropertiesToLoad.Add("description");
foreach (SearchResult groupSr in groupDs.FindAll())
...

当我获得组 DirectoryEntry 时,在 foreach 循环中,我可以访问大约 16 个不同的属性,而不仅仅是我指定的两个属性(distinguishedName,description)

【问题讨论】:

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


    【解决方案1】:

    您要限制的东西是您的SearchResult 对象中可用/填充的属性 - 您可以在foreach 循环中直接访问这些属性:

    DirectoryEntry baseEntry = new DirectoryEntry(rootPath, null, null, AuthenticationTypes.FastBind);
    
    DirectorySearcher groupSearcher = new DirectorySearcher(baseEntry);
    groupSearcher.Filter = "(objectClass=group)";
    
    groupSearcher.PropertiesToLoad.Add("distinguishedName");
    groupSearcher.PropertiesToLoad.Add("description");
    
    foreach (SearchResult groupSr in groupSearcher.FindAll())
    {
       if(groupSr.Properties["description"] != null && groupSr.Properties["description"].Count > 0)
       {
          string description = groupSr.Properties["description"][0].ToString();
       }
    
      .....
    } 
    

    您不能限制实际 DirectoryEntry 的属性 - 因此,如果您获取每个 SearchResult 的目录条目 - 您可以完全访问所有内容。但重点是您可以定义您需要的属性,并在SearchResult直接 访问这些属性,无需 不必返回底层DirectoryEntry

    【讨论】:

      【解决方案2】:

      原来的答案是正确的,但是如果您确实需要使用DirectoryEntry 并且想要访问特定属性,请确保在访问值之前通过RefreshCache 加载它:

      dirEntry.RefreshCache(new [] { "mail", "displayName" });
      var email = (string) dirEntry.Properties["mail"]?.Value;
      var displayName = (string) dirEntry.Properties["displayName"]?.Value;
      

      这样,只有“mail”和“displayName”会从此条目加载。

      更多信息here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-22
        • 2017-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多