Skip to main content
 首页 » 编程设计

c#之LDAP 路径问题

2024年02月23日23birdshome

我正在使用 LDAP,但我是新手。

有没有办法在只知道用户名、密码、服务器名的情况下获取域

我正在尝试这样做:

string ldapPath = "LDAP://serverName"; 
string uid = username; 
string password = pwd; 
string qry = String.Format("(uid={0})", uid); 
string adsPath = String.Empty; 
 
try 
{ 
    DirectoryEntry nRoot = new DirectoryEntry(ldapPath, null, null, AuthenticationTypes.Anonymous); 
 
    DirectorySearcher ds = new DirectorySearcher(nRoot, qry); 
    SearchResult sr = ds.FindOne(); 
 
    if (sr != null) 
    { 
       // we want to retrieve the DN like this: "uid=myuser,ou=People,dc=findlay,dc=edu 
       ldapPath = sr.Path; //update where we will bind next 
    } 

除非我改变,否则这不起作用

 string ldapPath = "LDAP://serverName"; 

到

 string ldapPath = "LDAP://serverName/DC=mydomain,DC=com"; 

任何帮助..??

谢谢

编辑 rootDSE

string defaultNamingContext; 
 
using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://serverName/rootDSE", null, null, AuthenticationTypes.Anonymous)) 
{ 
    defaultNamingContext = rootDSE.Properties["rootDomainNamingContext"].Value.ToString(); 
} 

我也觉得这是解决方案,但目前对我不起作用。请帮忙!

请您参考如下方法:

RootDSE 不是服务器绑定(bind)的 - 试试这个:

string defaultNamingContext; 
 
using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://rootDSE", null, null, AuthenticationTypes.Anonymous)) 
{ 
    defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); 
} 

或者,如果您使用的是 .NET 3.5 和更新版本,则可以改用 PrincipalContext,它可以在没有任何路径的情况下构建 - 它只会选择您连接到的默认域:

PrincipalContext context = new PrincipalContext(ContextType.Domain); 

您应该查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在这里阅读所有相关内容(即 .NET 3.5 和更新版本):