UserPrincipals.GetAuthorizationGroups An error (1301) occurred while enumerating the groups. After upgrading to Server 2012 Domain Controller

后端 未结 10 1301
陌清茗
陌清茗 2020-12-29 21:17

Research:

Similar Issue with workaround, but not actual solution to existing problem

Similar issue pointing to Microsoft End Point update as

10条回答
  •  盖世英雄少女心
    2020-12-29 22:02

    Here's my solution. It seems to work consistently well. Because the problem happens when iterating over the collection, I use a different approach when iterating in order to handle the exception without blocking the actual iterating:

    private string[] GetUserRoles(string Username)
    {    
        List roles = new List();
        try
        {
            string domain = Username.Contains("\\") ? Username.Substring(0, Username.IndexOf("\\")) : string.Empty;
            string username = Username.Contains("\\") ? Username.Substring(Username.LastIndexOf("\\") + 1) : Username;
            if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(username))
            {
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain);
                UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, username);
                if (user != null)
                {
                    PrincipalSearchResult groups = user.GetAuthorizationGroups();
                    int count = groups.Count();
                    for (int i = 0; i < count; i++)
                    {
                        IEnumerable principalCollection = groups.Skip(i).Take(1);
                        Principal principal = null;
                        try
                        {
                            principal = principalCollection.FirstOrDefault();
                        }
                        catch (Exception e)
                        {
                            //Error handling...
                            //Known exception - sometimes AD can't query a particular group, requires server hotfix?
                            //http://support.microsoft.com/kb/2830145
                        }
    
                        if (principal!=null && principal is GroupPrincipal)
                        {
                            GroupPrincipal groupPrincipal = (GroupPrincipal)principal;
                            if (groupPrincipal != null && !string.IsNullOrEmpty(groupPrincipal.Name))
                            {
                                roles.Add(groupPrincipal.Name.Trim());
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            //Error handling...
        }
        return roles.ToArray();
    }
    

提交回复
热议问题