从 C# 中的 DirectoryOperationException 获取信息

LeG*_*GEC 7 c# exception active-directory

我们有一个 C# 项目,它与 Active Directory 服务交互。

对于上下文:我们使用 System.DirectoryServices.Protocols 命名空间中的对象,即:

  • LdapConnection 连接到服务器
  • SearchRequest 扫描条目
  • DirSyncRequestControl 在 SearchRequest 上使用 DirSync 功能

我们在理解触发 DirectoryOperationException 的错误时陷入了困境,然后才意识到错误的描述未包含在 中exception.Message,而是进一步嵌套在异常对象中。

我们过去在捕获此类错误时有一个非常简单的异常日志记录:

catch (DirectoryOperationError de) {
    log("ERROR directory error {0} : {1}", de.GetType(), de.Message);
    throw;
}
Run Code Online (Sandbox Code Playgroud)

我们现在有以下代码:

catch (DirectoryOperationException de)
{
    log("ERROR directory error {0} : {1}", de.GetType(), de.Message);

    var resp = de.Response;
    if (resp == null)
    {
        log("          -- no response object linked to exception --");
        throw;
    }

    log("ERROR     directoryresponse error message:'{0}'", resp.ErrorMessage);

    int errorCode;
    var hexCode = resp.ErrorMessage.Substring(0, 8);
    if (!int.TryParse(hexCode, System.Globalization.NumberStyles.HexNumber, null, out errorCode)){
        log("          -- could not figure out error code from '{0}' --", hexCode);
        throw;
    }

    var win32exception = new System.ComponentModel.Win32Exception(errorCode);
    var msg = win32exception.Message;

    log("ERROR     errcode:{0} : {1}", errorCode, msg);

    throw;
}
Run Code Online (Sandbox Code Playgroud)

它在我的“hocus pocus”规模上排名相当高(特别是我们依赖以 8 个字符长的十六进制整数开头的字符串消息的部分)。

问题

是否有更直接的方法来访问底层 LDAPError 并使用 C# 将其转换为有意义的消息?

LeG*_*GEC 1

回到这个问题:

我意识到通过标准 LDAP 层与服务器通信只会得到一个标准LDAP Result,例如一个基本上带有一个 LDAP 错误代码(字段resultCode)和消息字符串(diagnosticMessage字段)的结构。

也许 Active Directory 可以在其响应中添加控件来指示 AD 特定信息,但看起来并没有。

所以总而言之,我认为没有更好的方法来解码该错误消息:库可能只会对消息字符串应用类似的处理,并希望它正在解码来自 Active 的消息目录——不是来自 OpenLDAP 或 Novell 或其他实现的消息,它恰好以有效的 8 字符十六进制代码开头。

在我们的例子中:由于我们的请求还包括与 AD 密切相关的控件(DirSync 控件),因此与 Active Directory 对话的置信度基本上是 100%。


我也许可以使用 Win32 API 特定函数,而不是通过 LDAP 连接,该函数可以返回 Win32 错误代码作为值,但当我们遇到此问题时,我还没有机会对此进行测试。


作为参考,此处列出了可能的 Win32 错误代码列表