2012-04-20 57 views
8

我想獲得該用戶在組列表獲取組的列表中給出UserPrincipal

這是我的代碼:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain.ac.uk", "DC=mydomain,DC=AC,DC=UK", "user", "password"); 

UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "MyUser"); 

PrincipalSearchResult<Principal> results = user.GetGroups(); 

foreach(Principal p in results) 
{ 
    Response.Write(p.Name); 
} 

當我跑,我得到了以下錯誤在線Response.Write(p.Name);

System.Runtime.InteropServices.COMException:指定的目錄服務屬性或值不存在。

當我檢查結果的計數時,它返回9,第一組爲DomainUsers。如何迭代列表中的所有9組?謝謝。

下面是用戶的名單,我得到:

enter image description here

+0

如何初始化PrincipalContext? – Damith 2012-04-20 10:34:00

+0

PrincipalContext ctx = new PrincipalContext(ContextType.Domain,「mydomain.ac.uk」,「DC = mydomain,DC = AC,DC = UK」,「user」,「password」); – TTCG 2012-04-20 10:34:59

+0

name屬性可能尚未填充(可能是因爲它來自與您查詢的域不同的域)。嘗試詢問DisplayName或DistinguishedName或SamAccountName或SID。 – Ben 2012-04-20 10:47:26

回答

1

嘗試像

foreach(Principal p in results) 
{ 
    if (p is GroupPrincipal) 
     Response.Write(p.DisplayName); 
} 

我知道這聽起來很愚蠢,但它在過去一直爲我工作。您的結果看起來好像只能找到1個安全組和8個「其他」類型的組。這些「其他」組可能不具備這些屬性。

+0

對我而言,名稱更好(DisplayName爲空:'user.GetGroups()。OfType ()。Select(p => p.Name));' – 2017-06-05 18:01:02

5

當省略如PrincipalContext類中描述的LDAP容器屬性,運行代碼的用戶必須具有讀取權限這兩個默認User容器(即CN=Users,DC=yourDomain,DC=COM)和Computers容器(即CN=Computers,DC=yourDomain,DC=COM)。

如果用戶沒有所需的權限,您將收到以下錯誤信息:

指定的目錄服務屬性或值不存在

  • 「context.Container」扔'System.NullReferenceException'字符串的例外字符串 {System.NullReferenceException}

  • ((new System.Linq.SystemCo re_EnumerableDebugView(組))。項[5])。說明」 投擲類型的異常 'System.Runtime.InteropServices.COMException' 字符串 {System.Runtime.InteropServices.COMException}

請檢查我的博客文章 Authentication Problems with PrincipalContext

+0

如果有人刪除了域中的計算機容器問題,你也會得到這個錯誤。看在上帝的份上...有人刪除了這個東西。 – 2018-01-30 21:19:43

+0

任何試圖使用'this.RequestContext.Principal.IsInRole(「廣告組名稱」)'的人都會拋出異常並返回false,這是一個可能的原因。恢復CN和權限爲我解決了這個問題。 – 2018-02-08 18:41:37

相關問題