尝试访问使用System.DirectoryServices时卸载的应用程序域

问题描述:

我们已经实现了对Active Directory进行身份验证并使用System.DirectoryServices的成员资格提供程序。 在带有webdev服务器的Visual Studio 2010上的ASP.Net MVC 3应用程序中使用此成员资格提供程序时,我们有时(6次中有1次)在登录应用程序时遇到异常。尝试访问使用System.DirectoryServices时卸载的应用程序域

System.IO.FileNotFoundException: Could not load file or assembly 'System.Web' or one of its dependencies. The system cannot find the file specified. 
File name: 'System.Web' 
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) 
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) 
at System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, StackCrawlMark& stackMark) 
at System.DirectoryServices.AccountManagement.UnsafeNativeMethods.IADsPathname.Retrieve(Int32 lnFormatType) 
at System.DirectoryServices.AccountManagement.ADStoreCtx.LoadDomainInfo() 
at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName() 
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) 
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() 
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups() 

=== Pre-bind state information === 
LOG: DisplayName = System.Web (Partial) 
WRN: Partial binding information was supplied for an assembly: 
WRN: Assembly Name: System.Web | Domain ID: 2 
WRN: A partial bind occurs when only part of the assembly display name is provided. 
WRN: This might result in the binder loading an incorrect assembly. 
WRN: It is recommended to provide a fully specified textual identity for the assembly, 
WRN: that consists of the simple name, version, culture, and public key token. 
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue. 
Calling assembly : HibernatingRhinos.Profiler.Appender, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0774796e73ebf640. 

调用程序集是HibernatingRhinos.Profiler.Appender所以log4net的配置禁用探查后,我们到了真正的例外:

System.AppDomainUnloadedException: Attempted to access an unloaded appdomain. (Except 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() 
at System.DirectoryServices.AccountManagement.ADStoreCtx.get_DnsDomainName() 
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p) 
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroupsHelper() 
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups() 

异常总是以同样的方法抛出,但对于现在我们无法随机地重现它,但大约6次中有1次。 但是,当使用IIs代替内置的Visual Studio 2010 Web服务器时,我们并没有得到例外。

当在Visual Studio webdev的上下文中使用多个appdomains时,它可能与赛车条件有关,但这只是猜测。 我们真的很想知道问题的原因是什么,因为我们不希望在生产环境中出现这些异常情况。

我们发现2类似的情况,但都没有找到真正的解决办法:

http://our.umbraco.org/forum/developers/extending-umbraco/19581-Problem-with-custom-membership-and-role-provider

http://forums.asp.net/t/1556949.aspx/1

更新18-05-2011

的代码量最小(在asp.net mvc)重现异常,其中userName是您的Active Directory登录名。

using System.DirectoryServices.AccountManagement; 
using System.Web.Mvc; 

namespace ADBug.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      string userName = "nickvane"; 
      var principalContext = new PrincipalContext(ContextType.Domain); 

      UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(
       principalContext, 
       IdentityType.SamAccountName, 
       userName); 

      if (userPrincipal != null) 
      { 
       PrincipalSearchResult<Principal> list = userPrincipal.GetAuthorizationGroups(); 
      } 

      return View(); 
     } 
    } 
} 

唉,异常仍然是随机发生的,所以没有完全可重现的错误。

+0

的问题也被提交给微软:[http://connect.microsoft.com/VisualStudio/feedback/details/566463 /试图访问一个卸载应用程序域异常从hresult-0x80131014 - 当调用getauthorizationgroups] – nickvane 2011-05-05 09:04:48

+0

我遇到同样的问题,当使用ActiveDirectoryMembershipProvider。对我来说,当我第一次调用Membership.ValidateUser()时它正在发生,它正在尝试创建提供程序。 – 2012-01-12 13:12:57

这里是我的什么作品(.NET 4):

取而代之的是:

principalContext = new PrincipalContext(ContextType.Domain) 

创建域串的主要方面,以及:

例如

principalContext = new PrincipalContext(ContextType.Domain,"MYDOMAIN") 

它应该固定在4.5。 查看评论,尚未修复,但添加第二个参数仍然可以解决问题。

+7

我使用4.5并看到错误,但此修复似乎仍然有帮助。 – 2013-08-08 22:16:59

+0

指定服务器名称适用于我,但几天后,我得到相同的错误。当我运行SysInternals Active Directory服务器并连接时未指定服务器名称时,将加载树并显示服务器名称。然后我使用该服务器名称作为我的新参数。但是,每次服务器名称更改时,我都无法发布新代码。它为什么改变?负载均衡?我能做什么?获取一个列表并尝试所有? – ChadD 2016-06-07 21:58:38

+0

我在Windows Server 2012中遇到了这个问题,但这个答案适用于我。我可以从用户名开头取得域名,所以没有麻烦。 – CompanyDroneFromSector7G 2016-09-14 13:38:48

我们已经通过重试对GetAuthorizationGroups的调用,但是在两者之间休眠的情况下在代码中解决了它。它解决了我们的问题,但我对此并不满意。

private PrincipalSearchResult<Principal> GetAuthorizationGroups(UserPrincipal userPrincipal, int tries) 
{ 
    try 
    { 
     return userPrincipal.GetAuthorizationGroups(); 
    } 
    catch (AppDomainUnloadedException ex) 
    { 
     if (tries > 5) 
     { 
      throw; 
     } 
     tries += 1; 
     Thread.Sleep(1000); 
     return GetAuthorizationGroups(userPrincipal, tries); 
    } 
} 

如果我们得到异常,那么1重试显然就足够了。

这个解决方案真的很慢,例如当你在web应用中使用GetAuthorizationGroups的时候,经常会调用GetAuthorizationGroups,这会让网站变得非常慢。我的工作是实现了som缓存,而第一次之后,它的速度更快了。我也在重试,因为异常仍然发生。

首先我重写GetRolesForUser方法并实现缓存。

public override string[] GetRolesForUser(string username) 
    { 
     // List of Windows groups for the given user. 
     string[] roles; 

     // Create a key for the requested user. 
     string cacheKey = username + ":" + ApplicationName; 

     // Get the cache for the current HTTP request. 
     Cache cache = HttpContext.Current.Cache; 
     // Attempt to fetch the list of roles from the cache. 
     roles = cache[cacheKey] as string[]; 
     // If the list is not in the cache we will need to request it. 
     if (null == roles) 
     { 
      // Allow the base implementation to load the list of roles. 
      roles = GetRolesFromActiveDirectory(username); 
      // Add the resulting list to the cache. 
      cache.Insert(cacheKey, roles, null, Cache.NoAbsoluteExpiration, 
       Cache.NoSlidingExpiration); 
     } 

     // Return the resulting list of roles. 
     return roles; 
    } 

GetRolesFromActiveDirectory看起来像这样。

public String[] GetRolesFromActiveDirectory(String username) 
    {    
     // If SQL Caching is enabled, try to pull a cached value.);)); 
     if (_EnableSqlCache) 
     { 
      String CachedValue; 
      CachedValue = GetCacheItem('U', username); 
      if (CachedValue != "*NotCached") 
      { 
       return CachedValue.Split(','); 
      } 
     } 

     ArrayList results = new ArrayList(); 
     using (PrincipalContext context = new PrincipalContext(ContextType.Domain, null, _DomainDN)) 
     { 
      try 
      {      
       UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username); 

       var tries = 0; 
       var groups = GetAuthorizationGroups(p, tries); 

       foreach (GroupPrincipal group in groups) 
       { 
        if (!_GroupsToIgnore.Contains(group.SamAccountName)) 
        { 
         if (_IsAdditiveGroupMode) 
         { 
          if (_GroupsToUse.Contains(group.SamAccountName)) 
          { 
           results.Add(group.SamAccountName); 
          } 
         } 
         else 
         { 
          results.Add(group.SamAccountName); 
         } 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       throw new ProviderException("Unable to query Active Directory.", ex); 
      } 
     } 
     // If SQL Caching is enabled, send value to cache 
     if (_EnableSqlCache) 
     { 
      SetCacheItem('U', username, ArrayListToCSString(results)); 
     } 

     return results.ToArray(typeof(String)) as String[]; 
    } 

最后一个方法是GetAuthorizationGroups,它看起来像这样。

private PrincipalSearchResult<Principal> GetAuthorizationGroups(UserPrincipal userPrincipal, int tries) 
    { 
     try 
     { 
      return userPrincipal.GetAuthorizationGroups(); 
     } 
     catch(FileNotFoundException ex) 
     { 
      if (tries > 5) throw; 

      tries++; 
      Thread.Sleep(1000); 

      return GetAuthorizationGroups(userPrincipal, tries); 
     } 
     catch (AppDomainUnloadedException ex) 
     { 
      if (tries > 5) throw; 

      tries++; 
      Thread.Sleep(1000); 

      return GetAuthorizationGroups(userPrincipal, tries); 
     } 
    } 

我发现缓存这些角色会让它变得更快。希望这可以帮助某人。 干杯。

+0

我不知道你为什么被投票。有人关心解释吗?我认为这是更合理的工作。 – Reza 2012-04-04 13:44:23

+0

这是一个很好的建议,但我也指定了域名! – CompanyDroneFromSector7G 2016-09-14 13:37:20

我使用ActiveDirectoryMembershipProvider时遇到同样的问题。对我来说,当我第一次调用Membership.ValidateUser()并且框架试图创建提供者时,发生了这种情况。

我发现我的临时开发的计算机没有安装Visual Studio 2010 SP1,所以我安装了它,并且解决了这个问题对我来说。

转到项目属性/网络选项卡/服务器部分,并在复选框NTML认证检查。

这是必需的卡西尼(VS开发服务器)使用Windows身份验证。

+2

这种情况也发生在生产环境中的IIS上,并且发生在5次中的1次,因此它不是处于开启或关闭状态。 – nickvane 2012-02-27 09:15:19

我有同样的问题,我发现在this后作品的答案。似乎是仅将ContextType作为参数的PrincipalContext构造函数的问题。我知道这个帖子是老了,但想到我会在未来的链接它的人:)