如何从异常中获取 LDAP 错误代码

How to get the LDAP error codes from exception

我使用 DirectoryEntry

创建 LDAP 连接

我的问题如果有错误我必须知道错误代码

我的代码:

var domain = WebConfigurationManager.AppSettings["ONLINE-AD"];

var directoryEntry = new DirectoryEntry("LDAP://" + domain);
directoryEntry.Username = model.userName;
directoryEntry.Password = model.password;

var directorySearcher = new DirectorySearcher(directoryEntry);

try
{
    var f = directorySearcher.FindOne();
    result = true;
}
catch (Exception ex)
{
    result = false;
}

异常时我把代码缝在这里:

我怎样才能把 error code 取出来?

您应该能够将它与一些正则表达式相匹配。例如:

catch (DirectoryServicesCOMException ex)
{
    Regex reg = new Regex(@"^(.*data )(?<ecode>\d*)");
    if(reg.IsMatch(ex.ExtendedErrorMessage))
    {
        GroupCollection groups = reg.Match(ex.ExtendedErrorMessage).Groups;
        errorCode = groups["ecode"].Value;
    }
}

正则表达式可能会被简化一点,但基本上它正在寻找

  • 行首 - ^
  • "data " 之前任意数量的任意字符并将其放入第一组 - (.*data )
  • 任意数量的数字,然后将其放入名为 ecode 的组中 - (?<ecode>\d*)

这仅在所有错误消息都具有相同格式的假设下有效。

您似乎无法从 DirectoryServicesCOMException 的数字参数中获取原始 LDAP 错误代码,因为 ADSI LDAP provider maps all the LDAP error codes to Win32 error codes.

您可以获得下一个:

var hresult = -2147023570; // -> 0x8007052e
// 0x8007052e is "LDAP_INVALID_CREDENTIALS Supplied credential is not valid."
var win32errorCode = (ushort)(0xFFFF & hresult); // --> 1326
// 1326 is "ERROR_LOGON_FAILURE The user name or password is incorrect."

列表ADSI System Error Codes