c#:无法获取用户的活动目录组

时间:2013-11-15 18:35:06

标签: c# c#-4.0 active-directory ldap c#-3.0

我的代码在我的本地计算机上运行,​​但在部署到开发服务器后不断收到错误消息。

错误讯息:

    System.ArgumentException: The (&(objectCategory=user)(objectClass=user)(|(userPrincipalName=)(distinguishedName=)(name=))) search filter is invalid.
       at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
       at System.DirectoryServices.SearchResultCollection.get_InnerList()
       at System.DirectoryServices.SearchResultCollection.get_Count()
       at System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRefHelper(Type principalType, String urnScheme, String urnValue, DateTime referenceDate, Boolean useSidHistory)
       at System.DirectoryServices.AccountManagement.ADStoreCtx.FindPrincipalByIdentRef(Type principalType, String urnScheme, String urnValue, DateTime referenceDate)
       at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
       at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue)
       at CLAdmin.Web.Infrastructure.Helpers.ADHelper.GetUserGroups(String userName)

这是我的代码:

    public List<string> GetUserGroups(string userName)
    {
        var result = new List<string>();

        try
        {
            using (var context = new PrincipalContext(ContextType.Domain, _ADDomain))
            {
                var user = UserPrincipal.FindByIdentity(context, userName);

                if (user != null)
                {
                    //var groups = user.GetAuthorizationGroups();
                    var groups = user.GetGroups();

                    foreach (Principal p in groups)
                    {
                        if (p is GroupPrincipal)
                        {
                            result.Add(p.Name);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            _logger.Error("An error happened in GetUserGroups", ex);
        }

        return result;
    }

2 个答案:

答案 0 :(得分:1)

搜索请求中使用的过滤器必须包含断言。像(attributeName=)这样的构造不起作用,并且正如错误消息所示,是无效的。

过滤器是

  • 平等:(attributeName=attributeValue)
  • substring:(attributeName=attributeVa*)
  • 目前:(attributeName=*)

和其他一些类型。有关过滤器的讨论,请参阅:

答案 1 :(得分:1)

您正在使用的FindByIdentity方法的工作方式是(最终,在调用链的某个位置)根据您传入的用户名构建查询。

鉴于异常在filter子句中显示空字符串,我怀疑你传入的用户名是null还是空。在方法的顶部添加一个参数检查,以验证userName参数不是null或为空(我建议抛出System.ArgumentException或其后代之一的实例,我打赌你会看到异常,而不是你描述的那个。

相关问题