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