1

我正在使用 Active Directory 对登录到公司 Intranet 上的 ASP.NET 网站的用户进行身份验证。我在以下代码行中收到“句柄无效”的错误:

Dim entry As DirectoryEntry = New DirectoryEntry(path, domainAndUsername, Password)

这是我用来进行身份验证的代码。Dim entry As DirectoryEntry = New DirectoryEntry(path, domainAndUsername, Password)

    Try
        'Bind to the native AdsObject to force authentication.          

        Dim obj As Object = entry.NativeObject
        Dim search As DirectorySearcher = New DirectorySearcher(entry)

        search.Filter = "(SAMAccountName=" & Username & ")"
        search.PropertiesToLoad.Add("cn")
        Dim result As SearchResult = search.FindOne()

        If (result Is Nothing) Then
            Return False
        End If

        'Update the new path to the user in the directory.
        '_path = result.Path
        '_filterAttribute = CType(result.Properties("cn")(0), String)

    Catch ex As Exception
        Throw New Exception("Error authenticating user. " & ex.Message)
    End Try

如何追踪此异常?Visual Studio 说它是 CryptographicException

谢谢

4

1 回答 1

1

假设您使用的是 .NET 3.5.... 并且认为代码可以很好地转换为 VB,您可以使用内置方法。

public bool isValidUser(string password,string username,string domain)
        {
            var isValid = false;
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
            {
                isValid = pc.ValidateCredentials(username, password);
            }
            return isValid;
        }

我知道它不能回答这样的问题,但可以避免首先出现异常

于 2013-10-17T07:49:19.120 回答