为什么无法通过PrincipalContext联系到Active Directory服务器?

6
我在使用WinForm应用程序访问Active Directory时遇到了一些问题。我的目标是在Active Directory中创建用户并查询用户。
以下是查找用户的代码片段:
public bool FindUser(string username)
{
    using (PrincipalContext context = new PrincipalContext(
        ContextType.Domain, 
        this.domainName, 
        this.DomainUserName, 
        this.DomainPassword))
    {                
        UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
        return (user != null) ? true : false;
    }
}

我无法基于给定的参数创建PrincipalContext对象。我遇到了以下异常:

Exception: The server could not be contacted.

内部异常说明:

Inner Exception: The LDAP server is unavailable.

在域名运行时,我可以对其进行ping测试并连接到该域名。

3个回答

1
你可以尝试下面的代码。
    public bool FindUser2(string userName)
    {
        try
        {
            DirectoryContext context = new DirectoryContext(
                DirectoryContextType.Domain,
                domainName,
                domainName + @"\" + domainUserName,
                domainPassword);
            DirectoryEntry domainEntry = Domain.GetDomain(context).GetDirectoryEntry();
            DirectorySearcher searcher = new DirectorySearcher(domainEntry,
                                                               "(|(objectCategory=user)(cn=" + domainUserName + "))");
            SearchResult searchResult = searcher.FindOne();
            return searchResult != null;
        }
        catch
        {
            return false;
        }
    }

1
你可以使用以下代码:
objectPath = "LDAP://CN=SC-5515_2,OU=Forus,DC=**MyDomainName**,DC=no";

public static bool Exists(string objectPath)
{
    return DirectoryEntry.Exists(objectPath);
}

这是我用于此的代码。如果在Active Directory中存在任何对象,则测试运行良好。

我在连接指定的Active Directory时遇到了错误。 - Mohsan
您需要发布更多信息。代码有效,如果出现问题,则可能是传递了错误的参数。 - EKS
对于我的本地域,它运行良好。但我无法在此域中创建用户。因此,为了测试目的,我在虚拟机上安装了Windows 2003服务器,并配置了域控制器。对于这个虚拟机,我无法查询Active Directory。 - Mohsan
我们的代码需要加入到我们想要查询的域中吗?目前我的计算机是“Care”域的一部分,而我的虚拟机则属于“TestDomain”。 - Mohsan
是的,或者你必须对另一个域进行身份验证。 - EKS
我正在传递用户名和密码以对其他域进行身份验证。 - Mohsan

0

您还可以考虑使用System.DirectoryServices.Protocols来访问其他域。这可能会有点陡峭的学习曲线,但速度更快,更灵活 - 例如,您可以进行适当的异步搜索。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接