我正在创建一个使用Active Directory的ASP.NET Intranet网站,我正在尝试获取用户所属的所有组,甚至是子组等...这意味着我必须使用递归方法来加载所有ArrayList中的组遵循此处给出的示例:https://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C
因此,我有一种方法可以根据组成员资格递归填充ArrayList:
public ArrayList AttributeValuesMultiString(string attributeName, string objectDn,
ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ldapConnection = new DirectoryEntry(objectDn);
PropertyValueCollection valueCollection = ldapConnection.Properties[attributeName];
IEnumerator en = valueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ldapConnection.Close();
ldapConnection.Dispose();
return valuesCollection;
}
我用其他方法打电话:
public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn, groupMemberships, recursive);
}
使用recursive
布尔值我可以构建我的组的arraylist,但第一种方法可以用于其他多字符串对象加载。现在,当我通过简单调用方法
//adManager is an instance of the class containing the methods above
//groups is an ArrayList
//testChain is my distinguishedName
groups = adManager.Groups(testChain, true);
foreach (var g in groups)
Console.WriteLine(g.ToString());
我有以下例外:
System.Runtime.InteropServices.COMException : Unspecified error
我有异常的地方是作业:
PropertyValueCollection valueCollection = ldapConnection.Properties[attributeName];
我真的没有看到这个问题,特别是这个方法是在另一个SO线程上推荐的,所以我猜它是有用的
编辑似乎我的问题来自身份验证问题。我在测试代码中添加了模拟,但仍然有例外:
using (HostingEnvironment.Impersonate())
{
var domainContext = new PrincipalContext(ContextType.Domain, "radiofrance.rootad.inetrf");
var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.Name, "Users");
if (groupPrincipal != null)
{
groups = adManager.Groups(testChain, true);
foreach (var g in groups)
Console.WriteLine(g.ToString());
}
else
Console.WriteLine("Fail");
}