Попытка доступа к выгруженному домену приложения при использовании системы.Каталог



мы реализовали поставщик членства, который аутентифицируется в Active Directory, и он использует систему.Каталог.
При использовании этого поставщика членства в ASP.Net приложение MVC 3 на Visual Studio 2010 с сервером webdev мы иногда (1 из 6 раз) получаем исключение при входе в приложение.



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.Профилировщик.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()


исключение всегда выбрасывается одним и тем же методом, но пока мы не можем воспроизвести его, как это происходит случайным образом, но примерно 1 из 6 раз.
Однако мы не получаем исключение при использовании IIs вместо встроенного веб-сервера Visual Studio 2010.



Это, вероятно, имеет какое-то отношение к гоночным условиям при использовании нескольких доменов приложений в контексте 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



обновление 18-05-2011



наименьшее количество код (в asp.net в MVC), чтобы воспроизвести исключение, где имя пользователя-это ваш активный каталог столбце loginname.



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();
}
}
}


увы, исключение по-прежнему происходит случайным образом, поэтому нет полностью воспроизводимой ошибки.

521   6  

6 ответов:

вот что работает для меня (.Net 4):

вместо этого:

principalContext = new PrincipalContext(ContextType.Domain)

создайте основной контекст со строкой домена, а также:

например.

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

это должно быть закреплено в 4.5. см. комментарий, еще не исправлен, но добавление второго аргумента все еще работает как обходной путь.

мы решили это в коде, повторяя вызов 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 повтор, по-видимому, достаточно.

Это решение действительно медленно, и когда, например, когда вы используете это в веб-приложении GetAuthorizationGroups вызывается очень часто, что делает сайт очень медленным. Я работал реализовал сом кэширование вместо этого, что делает намного быстрее после первого раза. Я также повторяю попытку, потому что исключение все еще происходит.

сначала я переопределяю метод 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);
        }
    }

я узнал, что кэширование ролей делает его намного быстрее. Надеюсь, это кому-то поможет. Овации.

Я столкнулся с той же проблемой при использовании ActiveDirectoryMembershipProvider. Для меня это происходило, когда я звонил членство.ValidateUser () в первый раз, и платформа пыталась создать поставщика.

Я заметил, что на моем временном компьютере разработки не установлен Visual Studio 2010 SP1, поэтому я установил его, и это решило проблему для меня.

У меня была такая же проблема, и я нашел ответ в этой почта работает. Кажется, проблема с конструктором PrincipalContext, который принимает только ContextType в качестве параметра. Я знаю, что этот пост старый, но думал, что я свяжу его для любого в будущем :)

перейдите в раздел свойства проекта / веб-вкладка / серверы и установите флажок для проверки подлинности NTML.

Это необходимо для Cassini (VS Development Server), чтобы использовать проверку подлинности Windows.

Comments

    Ничего не найдено.