尝试从 AD 检索用户主体名称时索引超出范围

本文关键字:索引 范围 AD 检索 用户主体 | 更新日期: 2023-09-27 17:55:59

我被难住了。

我正在尝试从AD获取用户主体名称,如下所示:

DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", UserName);
SearchResult result = search.FindOne();    
DirectoryEntry entry = result.GetDirectoryEntry();
_UPN = entry.Properties["userPrincipalName"][0].ToString();

但这给了我:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

谁能告诉我为什么会这样?

编辑:此代码获取当前用户的 SSID。 我需要在我在文本框中输入的任何用户上执行此操作。

WindowsIdentity windowsId = new WindowsIdentity(WindowsIdentity.GetCurrent().Token);
_SSID = windowsId.User.ToString()

尝试从 AD 检索用户主体名称时索引超出范围

我相信

问题是因为您将userPrincipalName条目视为值数组。 尝试按如下方式修改代码:

DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");
search.Filter = String.Format("(SAMAccountName={0})", UserName);
SearchResult result = search.FindOne();    
DirectoryEntry entry = result.GetDirectoryEntry();
_UPN = entry.Properties["userPrincipalName"].Value.ToString();

请注意,我将最后一行从 [0] 更改为值。 这应该可以解决您的问题。

我要说的一件事是,在尝试读取此值之前,我会进行一些检查。 在某些情况下,用户没有 UPN。 在这种情况下,当您尝试访问该字段时,代码会引发错误(该字段不存在,因此您只需要确保它不为 null)。

如果你使用的是 .NET 3.5 及更高版本,则应查看 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。在这里阅读所有关于它的信息:

在 .NET Framework 3.5 中管理目录安全主体

基本上,您可以定义域上下文并在 AD 中轻松查找用户和/或组:

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find user by name
UserPrincipal user = UserPrincipal.FindByIdentity(UserName);
if(user != null)
{
    string upn = user.UserPrincipalName;
}

新的 S.DS.AM 使得在AD中玩用户和组变得非常容易:

避免异常(如果有效)的明显做法是

if (entry.Properties["userPrincipalName"].Count > 0)
{
    _UPN = entry.Properties["userPrincipalName"][0].ToString();
}

但是,如果您应该获得有效的结果而您没有,那么我会检查 LDAP 连接字符串等。可以使用一些 LDAP 浏览器(商业 + 试用版)来正确获取连接字符串。