【问题标题】:Attempted to access an unloaded appdomain when using System.DirectoryServices使用 System.DirectoryServices 时尝试访问已卸载的应用程序域
【发布时间】:2011-08-19 04:52:41
【问题描述】:

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

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 的上下文中使用多个应用程序域时,这可能与赛车条件有关,但这只是猜测。 我们真的很想知道问题的原因是什么,因为我们不希望在生产环境中出现这些异常。

我们发现了 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

2011 年 5 月 18 日更新

重现异常的最少代码量(在 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();
        }
    }
}

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

【问题讨论】:

标签: .net asp.net-mvc visual-studio-2010


【解决方案1】:

这对我有用(.Net 4):

而不是这个:

principalContext = new PrincipalContext(ContextType.Domain)

也使用域字符串创建主体上下文:

例如

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

应该在 4.5 中修复。查看评论,尚未修复,但添加第二个参数仍然可以作为解决方法。

【讨论】:

  • 我正在使用 4.5 并看到错误,但此修复似乎仍然有帮助。
  • 指定服务器名称对我有用,但几天后,我得到了同样的错误。当我运行 SysInternals Active Directory Server 并在未指定服务器名称的情况下进行连接时,会加载树并显示服务器名称。然后我使用该服务器名称作为我的新参数。但是,每次服务器名称更改时,我都无法发布新代码。为什么会改变?负载均衡?我能做些什么?获取一份清单并全部尝试?
  • 我在 Windows Server 2012 中遇到了这个问题,但这个答案对我有用。我可以从用户名的开头取域名,所以一点也不麻烦。
【解决方案2】:

我们通过重试对 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 次重试显然就足够了。

【讨论】:

    【解决方案3】:

    这个解决方案真的很慢,例如,当您在 Web 应用程序中使用它时,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);
            }
        }
    

    我发现缓存角色可以大大加快速度。希望这可以帮助某人。 干杯。

    【讨论】:

    • 我不确定你为什么被否决。有人愿意解释吗?我认为这是更合理的解决方法。
    • 这是一个很好的建议,虽然我也指定了域!
    【解决方案4】:

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

    我注意到我的临时开发计算机没有安装 Visual Studio 2010 SP1,所以我安装了它,这解决了我的问题。

    【讨论】:

      【解决方案5】:

      我也遇到了同样的问题,我在this postworks 中找到了答案。似乎是仅将 ContextType 作为参数的 PrincipalContext 构造函数的问题。我知道这篇文章很旧,但我想我将来会为任何人链接它:)

      【讨论】:

        【解决方案6】:

        转到项目属性/web 选项卡/服务器部分并选中 NTML 身份验证复选框。

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

        【讨论】:

        • 在生产环境中的 IIS 上也会发生这种情况,并且它会发生 5 次中的 1 次,因此它不是开启或关闭的情况。
        猜你喜欢
        • 2011-09-30
        • 1970-01-01
        • 2019-03-02
        • 1970-01-01
        • 1970-01-01
        • 2017-09-26
        • 2015-06-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多