我在MVC Web应用程序中使用c#on .Net 4时出现问题,当我查询Active Directory时,我经常收到错误: 尝试访问卸载应用程序域。 (HRESULT异常:0x80131014)。
奇怪的是,它会在一段时间内完美无缺地工作,然后它才会开始发生,然后再次消失。
我对函数进行了一些修改以使其工作,但它们似乎都失败了。我想知道我做错了什么,或者是否有更好的方法来做。
这是我当前的函数,它将接受loginId和PrincipalContext。 loginId可以是用户DisplayName ,即“John Smith”,或 DOMAINNAME \ josmi 。默认设置是使用其名字的前2个字母,然后使用其姓氏的前3个字母。如果不是这样,那里有一张支票。这部分很好。
public List<ADGroup> GetMemberGroups(string loginId, PrincipalContext principalContext, int tries = 0)
{
var result = new List<ADGroup>();
try
{
var samAccountName = "";
if (loginId.Contains(" "))
{
var fName = loginId.Split(Char.Parse(" "))[0].ToLower();
var sName = loginId.Split(Char.Parse(" "))[1].ToLower();
if (sName.Trim().Length == 2)
samAccountName = string.Format("{0}{1}", fName.StartsWith(".") ? fName.Substring(0, 4) : fName.Substring(0, 3), sName.Substring(0, 2));
else
samAccountName = string.Format("{0}{1}", fName.StartsWith(".") ? fName.Substring(0, 3) : fName.Substring(0, 2), sName.Substring(0, 3));
}
else
samAccountName = loginId.Substring(loginId.IndexOf(@"\") + 1);
var authPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountName);
if (authPrincipal == null)
throw new Exception(string.Format("authPrincipal is null for loginId - {0}", loginId));
var firstLevelGroups = authPrincipal.GetGroups();
AddGroups(firstLevelGroups, ref result);
}
catch
{
if (tries > 5)
throw;
tries += 1;
System.Threading.Thread.Sleep(1000);
GetMemberGroups(loginId, principalContext, tries);
}
return result;
}
private void AddGroups(PrincipalSearchResult<Principal> principal, ref List<ADGroup> returnList)
{
foreach (var item in principal)
{
if (item.GetGroups().Count() > 0)
AddGroups(item.GetGroups(), ref returnList);
returnList.Add(new ADGroup(item.SamAccountName, item.Sid.Value));
}
}
这个函数的调用方式如下:
MembershipGroups = ad.GetMemberGroups(user.SamAccountName, new PrincipalContext(ContextType.Domain));
我 SOMETIMES 获得的错误是:
System.AppDomainUnloadedException: 试图访问卸载 应用程序域。 (HRESULT的例外情况: 0x80131014)at System.StubHelpers.StubHelpers.InternalGetCOMHRExceptionObject(的Int32 hr,IntPtr pCPCMD,Object pThis)at System.StubHelpers.StubHelpers.GetCOMHRExceptionObject(的Int32 hr,IntPtr pCPCMD,Object pThis)at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADsPathname.Retrieve(的Int32 lnFormatType)at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo() 在 System.DirectoryServices.AccountManagement.ADStoreCtx.get_UserSuppliedServerName() 在 System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.BuildPathFromDN(字符串 dn)at System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.MoveNextPrimaryGroupDN() 在 System.DirectoryServices.AccountManagement.ADDNLinkedAttrSet.MoveNext() 在 System.DirectoryServices.AccountManagement.FindResultEnumerator
1.MoveNext() at System.DirectoryServices.AccountManagement.FindResultEnumerator
1.System.Collections.IEnumerator.MoveNext()
答案 0 :(得分:9)
Active Directory and nested groups 这个可能很有希望继承代码示例..
public IList<string> FindUserGroupsLdap(string username)
{
// setup credentials and connection
var credentials = new NetworkCredential("username", "password", "domain");
var ldapidentifier = new LdapDirectoryIdentifier("server", 389, true, false);
var ldapConn = new LdapConnection(ldapidentifier, credentials);
// retrieving the rootDomainNamingContext, this will make sure we query the absolute root
var getRootRequest = new SearchRequest(string.Empty, "objectClass=*", SearchScope.Base, "rootDomainNamingContext");
var rootResponse = (SearchResponse)ldapConn.SendRequest(getRootRequest);
var rootContext = rootResponse.Entries[0].Attributes["rootDomainNamingContext"][0].ToString();
// retrieve the user
string ldapFilter = string.Format("(&(objectCategory=person)(sAMAccountName={0}))", username);
var getUserRequest = new SearchRequest(rootContext, ldapFilter, SearchScope.Subtree, null);
var userResponse = (SearchResponse)ldapConn.SendRequest(getUserRequest);
// send a new request to retrieve the tokenGroups attribute, we can not do this with our previous request since
// tokenGroups needs SearchScope.Base (dont know why...)
var tokenRequest = new SearchRequest(userResponse.Entries[0].DistinguishedName, "(&(objectCategory=person))", SearchScope.Base, "tokenGroups");
var tokenResponse = (SearchResponse)ldapConn.SendRequest(tokenRequest);
var tokengroups = tokenResponse.Entries[0].Attributes["tokenGroups"].GetValues(typeof(byte[]));
// build query string this query will then look like (|(objectSid=sid)(objectSid=sid2)(objectSid=sid3))
// we need to convert the given bytes to a hexadecimal representation because thats the way they
// sit in ActiveDirectory
var sb = new StringBuilder();
sb.Append("(|");
for (int i = 0; i < tokengroups.Length; i++)
{
var arr = (byte[])tokengroups[i];
sb.AppendFormat("(objectSid={0})", BuildHexString(arr));
}
sb.Append(")");
// send the request with our build query. This will retrieve all groups with the given objectSid
var groupsRequest = new SearchRequest(rootContext, sb.ToString(), SearchScope.Subtree, "sAMAccountName");
var groupsResponse = (SearchResponse)ldapConn.SendRequest(groupsRequest);
// loop trough and get the sAMAccountName (normal, readable name)
var userMemberOfGroups = new List<string>();
foreach (SearchResultEntry entry in groupsResponse.Entries)
userMemberOfGroups.Add(entry.Attributes["sAMAccountName"][0].ToString());
return userMemberOfGroups;
}
private string BuildHexString(byte[] bytes)
{
var sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
sb.AppendFormat("\\{0}", bytes[i].ToString("X2"));
return sb.ToString();
}
这些更多用于信息目的
答案 1 :(得分:5)
我不知道PrincipalContext
是如何传入的,在这里,但是当我遇到这个错误时,我在自己的代码和研究中注意到了一件事,我有:
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext , strUserName);
strUserName
是某个用户的位置,即DOMAIN\johndoe
我正在调用该代码(在一个单独的函数中)并将UserPrincipal
对象作为up
返回并传递给:
using (PrincipalSearchResult<Principal> result = up.GetGroups())
{
// do something with result, here
}
result
不会为空,但在我检查了这个条件之后,我检查了result.Count() > 0
是否会失败(有时候 - 虽然我可以重新创建它的条件通过点击我的应用程序中调用此代码的特定选项卡会发生 - 即使相同的代码被称为我的应用程序的onload并且没有问题)。 Message
中的result
属性为Attempted to access an unloaded appdomain. (Exception from HRESULT: 0x80131014)
。
我在a similar post中找到了这个,我所要做的就是在PrincipalContext
中指定域名。由于我无法硬编码,因为我们在开发,测试和生产环境之间移动我们的代码,在这些环境中,每个域都有不同的域,我可以将其指定为Environment.UserDomainName
:
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
这为我摆脱了错误。
答案 2 :(得分:4)
此问题与Determine if user is in AD group for .NET 4.0 application
相同使用修补程序解决了ADSI中的错误。 Windows 7 SP1和Windows Server 2008 R2 SP1不包含此修复程序,因此需要在开发计算机和服务器环境中手动部署它。
答案 3 :(得分:0)
您可以输入一些日志来缩小问题范围。 Thread.Sleep
看起来不像Web应用程序中想要的那样:)
如果你得到例外,也许你可以用不同的方式处理它们。
我认为你的AppDomain正在回收,而AD正在做巫术。将记录添加到Application_End
也可以提供一些线索。
答案 4 :(得分:0)
试
public List<ADGroup> GetMemberGroups(string loginId, PrincipalContext principalContext, int tries = 0)
{
var result = new List<ADGroup>();
bool Done = false;
try
{
var samAccountName = "";
if (loginId.Contains(" "))
{
var fName = loginId.Split(Char.Parse(" "))[0].ToLower();
var sName = loginId.Split(Char.Parse(" "))[1].ToLower();
if (sName.Trim().Length == 2)
samAccountName = string.Format("{0}{1}", fName.StartsWith(".") ? fName.Substring(0, 4) : fName.Substring(0, 3), sName.Substring(0, 2));
else
samAccountName = string.Format("{0}{1}", fName.StartsWith(".") ? fName.Substring(0, 3) : fName.Substring(0, 2), sName.Substring(0, 3));
}
else
samAccountName = loginId.Substring(loginId.IndexOf(@"\") + 1);
var authPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, samAccountName);
if (authPrincipal == null)
throw new Exception(string.Format("authPrincipal is null for loginId - {0}", loginId));
var firstLevelGroups = authPrincipal.GetGroups();
AddGroups(firstLevelGroups, ref result);
Done = true;
}
catch
{
if (tries > 5)
throw;
tries += 1;
}
if ( ( !Done) && (tries < 6) )
{
System.Threading.Thread.Sleep(1000);
result = GetMemberGroups(loginId, principalContext, tries);
}
return result;
}
private void AddGroups(PrincipalSearchResult<Principal> principal, ref List<ADGroup> returnList)
{
if ( principal == null )
return;
foreach (var item in principal)
{
if (item.GetGroups().Count() > 0)
AddGroups(item.GetGroups(), ref returnList);
returnList.Add(new ADGroup(item.SamAccountName, item.Sid.Value));
}
}
当发生异常时,你从catch块再次调用该函数(取决于尝试的值)但是丢弃了它的返回值 - 所以即使第二个/第三个...调用工作你返回一个空结果给原来的来电者。 我改变了,所以结果不会再被丢弃......
在第二个函数中,在启动foreach之前,你从未检查过主体参数是否为null ...我也改变了它...
我从catch块catch中删除了递归(虽然我真的不确定这个更改是否有任何实际效果)。