8

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

从微软的例子在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); 
    } 
} 

如果我把从MSDN例子确切的代码并将其粘贴到我的应用程序,这是行不通的。到InetOrgPerson.FindByIdentity()的调用返回空,因为这样的:

if (null == InetOrgPerson.FindByIdentity(principalContext, UserName)) { 
    throw new Exception("bah"); 
} 

事实上,从InetOrgPerson.FindByIdentity()内,调用FindByIdentityWithType()返回NULL,因为这样:

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

然而,电话:

FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue) 

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

什么给?我希望微软自己的示例代码能够工作,但它并没有,所以我试图基于这个例子编写的代码自然也不起作用。有没有人做过这项工作?

提前致谢! James

回答

12

确保您正在搜索的用户实际上属于类inetOrgPerson

+2

是的,这是问题所在。我没有意识到我设置的'DirectoryObjectClass'属性将类绑定到AD中的类。所以现在我明白了,当我通过这个类的FindByIdentity进行搜索时,我将搜索范围限制在AD'inetOrgPerson'类中的对象,其中AD中没有任何对象。在我的情况下,我想将'DirectoryObjectClass'设置为'user'。 这实际上很酷。谢谢! – 2010-08-18 21:06:19

+0

令人惊叹,也为我解决了一个问题 – nokturnal 2013-05-30 17:21:52