这是我用来连接LDAP的代码
using (DirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", this.Host, ServerName)))
{
DirEntry.RefreshCache();
if (!string.IsNullOrEmpty(UserName))
{
DirEntry.Username = UserName;
DirEntry.Password = PassWord;
}
if (DirEntry.Properties.Contains("objectGUID"))
{
byte[] guiddatet = (byte[])DirEntry.Properties["objectGUID"].Value;
return new Guid(guiddatet);
}
运行代码时出现“服务器无法运行”错误消息。
有人可以告诉我,我做错了。 无论如何都要用直接LDAP查询替换上面的代码。
答案 0 :(得分:2)
您应该尝试将其拆分为单独的部分,这样可以更轻松地管理逻辑,并更容易找到错误发生的位置。在这种情况下,我通常采用以下方法:
LdapConnection
对象,以便设置所需的选项NetworkCredential
实例SearchResultEntry
,以便您可以处理属性您有几个选项可以帮助您实现这一目标,但我会尝试这样的事情:
//Delcare your Network Credential with the administrative Username, Password, and your active directory domain
var credentials = new NetworkCredential(userName, password, domain);
//Create a directory identifier and connection,
var ldapidentifier = new LdapDirectoryIdentifier(serverName, port, false, false);
var ldapconn = new LdapConnection(ldapidentifier, credentials);
接下来,请确保为您的特定实例设置正确的AuthType
。由于您通过端口389进行连接,因此只需使用AuthType.Basic
。
ldapconn.AuthType = AuthType.Basic;
正如您所问,使用此方法设置直接LDAP查询有一种非常简单的方法。我假设您正在sAMAccountName
进行搜索,但您可以根据需要进行修改:
string ldapFilter = "(&(objectCategory=person)(objectClass=user)(&(sAMAccountName={{UserYouAreTryingToFind}})))";
现在我们只需要设置搜索请求,然后相应地发送:
//Send the search request with our delimited attribute list
var getUserRequest = new SearchRequest(domain, ldapFilter, SearchScope.Subtree, AttributeList)
{SizeLimit = 1};
//Suppress any refferal creation from happening during the search
var SearchControl = new SearchOptionsControl(SearchOption.DomainScope);
getUserRequest.Controls.Add(SearchControl);
var userResponse = (SearchResponse)ldapconn.SendRequest(getUserRequest);
//This is where I load up the entry I've located,
SearchResultEntry ResultEntry = userResponse.Entries[0];
这应该返回您查询过的用户,以及您放入AttributeList
的所有属性。在此上下文中,AttributeList
只是属性名称的字符串数组(string[]
) - 在您的情况下,您将要添加一个名为“objectGUID”的文件。
至于阅读SearchResultEntry
上的属性,你可以完全按照原来的那样做:
if(ResultEntry.Attributes.Contains("objectGUID"))
{
// do some stuff here
}
这应该有助于你朝着正确的方向前进。
此外,如果您还没有wireshark的副本,我强烈建议您下载它 - 它在诊断活动目录的连接问题时非常有用。