扩展UserPrincipal; FindByIdentity()失败

Jam*_*ing 8 c# directoryservices active-directory account-management userprincipal

扩展UserPrincipal以利用其内置属性...当我们重载FindByIdentity()方法时遇到问题.

来自Microsoft的示例http://msdn.microsoft.com/en-us/library/bb384372%28VS.90%29.aspx(为简洁起见,不包括部分):

[DirectoryRdnPrefix("CN")]
[DirectoryObjectClass("inetOrgPerson")]
public class InetOrgPerson : UserPrincipal {

   // Implement the overloaded search method FindByIdentity
   public static new InetOrgPerson FindByIdentity(PrincipalContext context, 
                                                  string identityValue) {
       return (InetOrgPerson)FindByIdentityWithType(context,
                                                    typeof(InetOrgPerson),
                                                    identityValue);
   }

   // Implement the overloaded search method FindByIdentity
   public static new InetOrgPerson FindByIdentity(PrincipalContext context, 
                                                  IdentityType identityType, 
                                                  string identityValue) {
       return (InetOrgPerson)FindByIdentityWithType(context, 
                                                    typeof(InetOrgPerson), 
                                                    identityType,
                                                    identityValue);
   } 
}
Run Code Online (Sandbox Code Playgroud)

如果我从MSDN示例中获取确切的代码并将其粘贴到我的应用程序中,它就不起作用.调用InetOrgPerson.FindByIdentity()返回null,如下:

if (null == InetOrgPerson.FindByIdentity(principalContext, UserName)) {
     throw new Exception("bah");
}
Run Code Online (Sandbox Code Playgroud)

实际上,从内部InetOrgPerson.FindByIdentity()调用FindByIdentityWithType()返回null,如下:

if (null == FindByIdentityWithType(context, typeof(InetOrgPerson), identityType, identityValue) {
    throw new Exception("bah");
}
Run Code Online (Sandbox Code Playgroud)

但是,电话:

FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue)
Run Code Online (Sandbox Code Playgroud)

给了我想要的用户对象.除了我不能使用它,因为它不能被强制转换为InetOrgPerson我需要返回的对象.

是什么赋予了?我希望微软自己的示例代码可以工作,但事实并非如此,因此我尝试根据示例编写的代码自然也无法正常工作.有没有人做过这项工作?

提前致谢!詹姆士

Jus*_*tch 13

确保您要搜索的用户实际属于该类inetOrgPerson.

  • 是的,这就是问题所在.我没有意识到我设置的`DirectoryObjectClass`属性将类绑定到AD中的类.所以现在我明白,当我搜索这个类的'FindByIdentity`时,我将我的搜索限制在类'inetOrgPerson'的AD中的对象,其中我们的AD中没有.在我的例子中,我想将`DirectoryObjectClass`设置为'user'.这真的很酷.谢谢! (2认同)