System.DirectoryServices를 사용할 때 언로드 된 appdomain에 액세스하려고했습니다.
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 회입니다. 그러나 기본 제공 Visual Studio 2010 웹 서버 대신 II를 사용할 때 예외가 발생하지 않습니다.
Visual Studio webdev의 컨텍스트에서 여러 앱 도메인을 사용할 때 경주 조건과 관련이있을 수 있지만 추측 일뿐입니다. 프로덕션 환경에서 이러한 예외를 원하지 않기 때문에 문제의 원인이 무엇인지 정말로 알고 싶습니다.
2 개의 유사한 사례를 찾았지만 아무도 실제 해결책을 찾지 못했습니다.
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();
}
}
}
아아, 예외는 여전히 무작위로 발생하므로 완전히 재현 가능한 버그는 없습니다.
저에게 적합한 것은 다음과 같습니다 (.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가 매우 자주 호출되어 사이트를 매우 느리게 만듭니다. 대신 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[];
}
The last method is GetAuthorizationGroups and it looks like this.
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);
}
}
I found out that caching the roles makes it a whole lot faster. Hope this helps someone. Cheers.
I've encountered the same issue when using the ActiveDirectoryMembershipProvider. For me it was happening when I called Membership.ValidateUser() for the first time and the framework was trying to create the provider.
I noticed that my temporary development computer did not have Visual Studio 2010 SP1 installed so I installed it and that solved the problem for me.
I've had the same issue, and I have found the answer in this post works. Seems to be an issue with the PrincipalContext constructor that only takes a ContextType as a parameter. I know this post is old, but thought I would link it for anyone in the future :)
Go to project properties/web tab/Servers section and check in the checkbox for NTML authentication.
This is required for Cassini (VS Development Server) to use Windows authentication.
'Program Club' 카테고리의 다른 글
| [=]는 모든 지역 변수가 복사된다는 것을 의미합니까? (0) | 2020.12.01 |
|---|---|
| Java에서 무엇을 던질 수 있습니까? (0) | 2020.12.01 |
| 파이썬에서 모듈과 라이브러리의 차이점은 무엇입니까? (0) | 2020.12.01 |
| 빌드 경로 Eclipse에 "Maven Managed Dependencies"라이브러리를 추가하는 방법은 무엇입니까? (0) | 2020.11.30 |
| 플롯 레이블에서 paste () 및 expression () 함수 결합 (0) | 2020.11.30 |