使用DirectoryServices对象时获取异常

时间:2013-10-16 18:57:19

标签: asp.net vb.net active-directory

我正在使用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

由于

1 个答案:

答案 0 :(得分: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;
        }

我知道它不会回答问题,但可以避免在第一时间获得例外