使用System.DirectoryServices时尝试访问已卸载的appdomain

时间:2011-05-05 09:03:26

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

我们已经实现了一个对Active Directory进行身份验证的成员资格提供程序,它使用的是System.DirectoryServices。 在带有webdev服务器的Visual Studio 2010上的ASP.Net MVC 3应用程序中使用此成员资格提供程序时,我们有时(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次。 但是,在使用II而不是内置的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();
        }
    }
}

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

6 个答案:

答案 0 :(得分:83)

这对我有用(.Net 4):

而不是:

principalContext = new PrincipalContext(ContextType.Domain)

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

E.g。

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

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

答案 1 :(得分:1)

我们在代码中通过重试对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次重试显然已经足够了。

答案 2 :(得分:1)

此解决方案非常慢,例如当您在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);
        }
    }

我发现缓存这些角色会让它变得更快。希望这有助于某人。 欢呼声。

答案 3 :(得分:1)

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

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

答案 4 :(得分:1)

我遇到了同样的问题,我在this帖子中找到了答案。似乎是PrincipalContext构造函数的问题,它只将ContextType作为参数。我知道这篇文章很老了,但我想以后会把它链接给任何人:)

答案 5 :(得分:-1)

转到项目属性/ Web选项卡/服务器部分,然后选中NTML身份验证复选框。

这是Cassini(VS Development Server)使用Windows身份验证所必需的。