在将此方法称为C#之前,必须保留Principal对象

时间:2015-05-25 17:16:59

标签: c#

我正在尝试从AD获取额外的用户信息。

  List<string> allUsers = new List<string>();
            PrincipalContext ctx2 = new PrincipalContext(ContextType.Domain, "FUNDACION", valor);     
            UserPrincipal qbeUser2 = new UserPrincipal(ctx2);

            qbeUser2.Enabled = true; // activo para autenticacion

            PrincipalSearcher srch2 = new PrincipalSearcher(qbeUser2);
            srch2.QueryFilter = qbeUser2;

           DirectoryEntry dirEntry = (qbeUser2.GetUnderlyingObject() as DirectoryEntry);  

我在这一行得到例外:

  

DirectoryEntry dirEntry =(qbeUser2.GetUnderlyingObject()as DirectoryEntry);

     

System.DirectoryServices.AccountManagement.dll中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理   附加信息:在调用此方法之前,必须保留Principal对象。

2 个答案:

答案 0 :(得分:0)

您是否可以访问UserPrincipal类的源代码,特别是GetUnderlyingObject()方法的源代码?

看起来该方法正在抛出异常。这可能是通过合同或偶然发生的。

如果期望抛出此异常(“按合同”),那么您应该将此方法调用包装在try/catch块中并相应地处理异常:

try {
    DirectoryEntry dirEntry = (qbeUser2.GetUnderlyingObject() as DirectoryEntry);
} catch (InvalidOperationException e) {
    // handle expected exception accordingly
}

否则,您应该在调用方法之前确保对象是持久的,就像异常消息所说的那样(docs here):

qbeUser2.Save();
DirectoryEntry dirEntry = (qbeUser2.GetUnderlyingObject() as DirectoryEntry);

答案 1 :(得分:0)

您需要先执行qbeUser2.Save()才能调用GetUnderlyingObject()