【问题标题】:Extending UserPrincipal; FindByIdentity() fails扩展用户主体; FindByIdentity() 失败
【发布时间】:2023-06-11 21:57:01
【问题描述】:

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

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

[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() 的调用返回null,如下所示:

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 对象。

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

提前致谢! 詹姆斯

【问题讨论】:

    标签: c# active-directory account-management directoryservices userprincipal


    【解决方案1】:

    确保您要搜索的用户确实属于 inetOrgPerson 类。

    【讨论】:

    • 是的,这就是问题所在。我没有意识到我设置的DirectoryObjectClass 属性将类绑定到AD 中的类。所以现在我明白了,当我通过这个类的FindByIdentity 进行搜索时,我将搜索限制在 AD 中的类“inetOrgPerson”中的对象,我们的 AD 中没有这些对象。就我而言,我想将DirectoryObjectClass 设置为“用户”。这实际上很酷。谢谢!
    • 太棒了,也为我解决了一个问题
    最近更新 更多