【问题标题】:How to connect to an active directory server?如何连接到活动目录服务器?
【发布时间】:2011-05-01 05:50:42
【问题描述】:

我正在使用以下代码连接到活动目录服务器并检索其用户。

但我的网络服务器不在子域中。我可以连接到它吗?

或者我应该包括它的IP地址或其他什么?

DirectoryEntry entry = new DirectoryEntry("LDAP://dps.com", "Raymond", "xxxxxxx");

DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = ("(&(objectCategory=person)(objectClass=user))");

foreach (SearchResult result in mySearcher.FindAll())
{
   ResultPropertyCollection myResultPropColl = result.Properties;
   DataRow dr=reader.Tables[0].NewRow();
   dr[0]=myResultPropColl["samaccountname"][0].ToString()+"@"+Domain;
   reader.Tables[0].Rows.Add(dr);
   Response.Write(myResultPropColl["samaccountname"][0].ToString());
}

【问题讨论】:

    标签: asp.net active-directory


    【解决方案1】:

    如果您使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在此处阅读所有相关信息:

    Managing Directory Security Principals in the .NET Framework 3.5

    基本上,您可以定义域上下文并在 AD 中轻松找到用户和/或组:

    // set up domain context - connects to the current default domain
    PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
    
    // find user by name
    UserPrincipal user = UserPrincipal.FindByIdentity("John Doe");
    
    // find all users in your AD directory - set up a "query-by-example" 
    // template to search for; here: a UserPrincipal, which is not locked out
    UserPrincipal userTemplate = new UserPrincipal(ctx);
    userTemplate.IsAccountLockedOut = false;
    
    // create a PrincipalSearcher, based on that search template
    PrincipalSearcher searcher = new PrincipalSearcher(userTemplate);
    
    // enumerate all users that this searcher finds
    foreach(Principal foundPrincipal in searcher.FindAll())
    {
       UserPrincipal foundUser = (foundPrincipal as UserPrincipal);
    
       // do something with the userTemplate
    }
    

    新的 S.DS.AM 让在 AD 中与用户和组一起玩变得非常容易:

    如果您无法升级到 S.DS.AM,您需要做的是确保使用正确的 LDAP 字符串连接到您的服务器。该字符串应该是这样的:

     LDAP://servername/OU=Users,DC=YourCompany,DC=com
    

    servername 是可选的 - 您也可以省略它。但 LDAP 字符串需要由至少一个 DC=xxxxx 字符串和可能的其他 LDAP 段组成。

    【讨论】:

      猜你喜欢
      • 2018-08-28
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      相关资源
      最近更新 更多