Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

ASP.NET에서 System.BadImageFormatException 예외가 발생하는 경우

대개, System.BadImageFormatException 예외가 발생하는 것은 플랫폼 설정이 맞지 않기 때문이고 이럴 때는 응용 프로그램이 정상적으로 실행되지 않을 수 있습니다.

System.BadImageFormatException
; https://www.sysnet.pe.kr/2/0/519

supportedRuntime 옵션과 System.BadImageFormatException 예외
; https://www.sysnet.pe.kr/2/0/1233

하지만, 때로는 이 예외를 Thrown 설정으로 켜놓으면 원치 않게 발생하는 경우도 있는데요. 예를 들어, 콜스택이 다음과 같은 상황으로 System.BadImageFormatException 예외가 발생할 수 있습니다.

>    mscorlib.dll!System.Reflection.RuntimeAssembly.nLoad(System.Reflection.AssemblyName fileName, string codeBase, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly locationHint, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks) + 0x25 bytes   
    mscorlib.dll!System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly reqAssembly, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks) + 0x15c bytes  
    mscorlib.dll!System.Reflection.RuntimeAssembly.InternalLoad(string assemblyString, System.Security.Policy.Evidence assemblySecurity, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool forIntrospection) + 0x54 bytes  
    mscorlib.dll!System.Reflection.RuntimeAssembly.InternalLoad(string assemblyString, System.Security.Policy.Evidence assemblySecurity, ref System.Threading.StackCrawlMark stackMark, bool forIntrospection) + 0x17 bytes 
    mscorlib.dll!System.Reflection.Assembly.Load(string assemblyString) + 0x1e bytes    
    System.Web.dll!System.Web.Configuration.CompilationSection.LoadAssemblyHelper(string assemblyName, bool starDirective) + 0x27 bytes 
    System.Web.dll!System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() + 0xc5 bytes    
    System.Web.dll!System.Web.Configuration.CompilationSection.LoadAssembly(System.Web.Configuration.AssemblyInfo ai) + 0x2e bytes  
    System.Web.dll!System.Web.Configuration.AssemblyInfo.AssemblyInternal.get() + 0x1a bytes    
    System.Web.dll!System.Web.Compilation.BuildManager.GetReferencedAssemblies(System.Web.Configuration.CompilationSection compConfig) + 0x8b bytes 
    System.Web.dll!System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() + 0x1a bytes    
    System.Web.dll!System.Web.Compilation.BuildManager.CallPreStartInitMethods(string preStartInitListPath, out bool isRefAssemblyLoaded) + 0x70 bytes  
    System.Web.dll!System.Web.Compilation.BuildManager.ExecutePreAppStart() + 0x7f bytes    
    System.Web.dll!System.Web.Hosting.HostingEnvironment.Initialize(System.Web.Hosting.ApplicationManager appManager, System.Web.Hosting.IApplicationHost appHost, System.Web.Configuration.IConfigMapPathFactory configMapPathFactory, System.Web.Hosting.HostingEnvironmentParameters hostingParameters, System.Security.Policy.PolicyLevel policyLevel, System.Exception appDomainCreationException) + 0x2a3 bytes   
    System.Web.dll!System.Web.Hosting.HostingEnvironment.Initialize(System.Web.Hosting.ApplicationManager appManager, System.Web.Hosting.IApplicationHost appHost, System.Web.Configuration.IConfigMapPathFactory configMapPathFactory, System.Web.Hosting.HostingEnvironmentParameters hostingParameters, System.Security.Policy.PolicyLevel policyLevel) + 0x18 bytes 
    [Appdomain Transition]  
    System.Web.dll!System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironment(string appId, System.Web.Hosting.IApplicationHost appHost, System.Web.Hosting.HostingEnvironmentParameters hostingParameters) + 0x157c bytes 
    System.Web.dll!System.Web.Hosting.ApplicationManager.CreateAppDomainWithHostingEnvironmentAndReportErrors(string appId, System.Web.Hosting.IApplicationHost appHost, System.Web.Hosting.HostingEnvironmentParameters hostingParameters) + 0x25 bytes    
    System.Web.dll!System.Web.Hosting.ApplicationManager.GetAppDomainWithHostingEnvironment(string appId, System.Web.Hosting.IApplicationHost appHost, System.Web.Hosting.HostingEnvironmentParameters hostingParameters) + 0x74 bytes  
    System.Web.dll!System.Web.Hosting.ApplicationManager.CreateObjectInternal(string appId, System.Type type, System.Web.Hosting.IApplicationHost appHost, bool failIfExists, System.Web.Hosting.HostingEnvironmentParameters hostingParameters) + 0x48 bytes   
    System.Web.dll!System.Web.Hosting.ProcessHost.StartApplication(string appId, string appPath, out object runtimeInterface) + 0x109 bytes 
    [Native to Managed Transition]  

보시면, bin 폴더의 모든 어셈블리를 로드하라는 메서드가 있는데 소스 코드를 보면 오류 원인을 알 수 있습니다.

internal Assembly[] LoadAllAssembliesFromAppDomainBinDirectory()
{
    string binDirectoryInternal = HttpRuntime.BinDirectoryInternal;
    Assembly assembly = null;
    Assembly[] assemblyArray = null;
    if (System.Web.Util.FileUtil.DirectoryExists(binDirectoryInternal))
    {
        FileInfo[] files = new DirectoryInfo(binDirectoryInternal).GetFiles("*.dll");
        if (files.Length != 0)
        {
            ArrayList list = new ArrayList(files.Length);
            for (int i = 0; i < files.Length; i++)
            {
                string assemblyNameFromFileName = Util.GetAssemblyNameFromFileName(files[i].Name);
                if (!assemblyNameFromFileName.StartsWith("App_Web_", StringComparison.Ordinal))
                {
                    if (!this.GetAssembliesCollection().IsRemoved(assemblyNameFromFileName))
                    {
                        assembly = this.LoadAssemblyHelper(assemblyNameFromFileName, true);
                    }
                    if (assembly != null)
                    {
                        list.Add(assembly);
                    }
                }
            }
            assemblyArray = (Assembly[]) list.ToArray(typeof(Assembly));
        }
    }
    if (assemblyArray == null)
    {
        assemblyArray = new Assembly[0];
    }
    return assemblyArray;
}

즉, bin 폴더의 모든 DLL을 로드해서 Assembly.Load를 해보는 것인데 만약 Native DLL이라도 있는 경우라면 여지없이 System.BadImageFormatException 예외가 발생합니다. 이것이 귀찮아서라도 System.BadImageFormatException 항목을 "Exception Settings"의 "Thrown" 항목에서 제외시켜야만 합니다.

다행히, 이를 비켜가는 방법이 있습니다. 이는 compilation 섹션에 의해 발생하는 것이므로 다음과 같이 원하는 항목에 대해 <remove />로 명시해 주면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...[생략]...

    <system.web>
        ...[생략]...

        <compilation debug="true" targetFramework="4.0">
            <assemblies>
                <remove assembly="db2app"/>

                <remove assembly="Microsoft.VisualStudio.Web.PageInspector.Loader, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
                <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
                <add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
            </assemblies>
        </compilation>
        ...[생략]...

    </system.web>
    ...[생략]...
</configuration>

위의 설정에서는 db2app.dll 파일을 로드할 필요 없다는 것을 알립니다.




그래도 ASP.NET 환경에서는 System.BadImageFormatException 예외가 발생하는 상황이 하나 더 있습니다. 예외 상황은 다음과 같습니다.

System.BadImageFormatException occurred
  HResult=-2146234344
  Message=Could not load file or assembly 'file:///D:\....WebSiteTest4\bin\db2app.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
  Source=mscorlib
  FileName=file:///D:\....WebSiteTest4\bin\db2app.dll
  FusionLog==== Pre-bind state information ===
LOG: Where-ref bind. Location = D:\....WebSiteTest4\bin\db2app.dll
LOG: Appbase = file:///D:/....WebSiteTest4/
LOG: Initial PrivatePath = D:\....WebSiteTest4\bin
Calling assembly : (Unknown).
===
LOG: This is an inspection only bind.
LOG: Using application configuration file: D:\....WebSiteTest4\web.config
LOG: Using host configuration file: C:\...\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///D:/....WebSiteTest4/bin/db2app.dll.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

  StackTrace:
       at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
       at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
  InnerException: 

콜 스택은 이렇고.

>    mscorlib.dll!System.Reflection.RuntimeAssembly.nLoad(System.Reflection.AssemblyName fileName, string codeBase, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly locationHint, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks) + 0x25 bytes   
    mscorlib.dll!System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly reqAssembly, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks) + 0x15c bytes  
    mscorlib.dll!System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity, System.Reflection.RuntimeAssembly reqAssembly, ref System.Threading.StackCrawlMark stackMark, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks) + 0x1e bytes  
    mscorlib.dll!System.Reflection.RuntimeAssembly.InternalLoadFrom(string assemblyFile, System.Security.Policy.Evidence securityEvidence, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm, bool forIntrospection, bool suppressSecurityChecks, ref System.Threading.StackCrawlMark stackMark) + 0x69 bytes   
    mscorlib.dll!System.Reflection.Assembly.ReflectionOnlyLoadFrom(string assemblyFile) + 0x24 bytes    
    Microsoft.Owin.Host.SystemWeb.dll!Owin.Loader.DefaultLoader.GetDefaultConfigurationString(System.Func<System.Reflection.Assembly,string[]> defaultTypeNames) + 0x18a bytes    
    Microsoft.Owin.Host.SystemWeb.dll!Owin.Loader.DefaultLoader.LoadImplementation(string startupName) + 0x69 bytes 
    Microsoft.Owin.Host.SystemWeb.dll!Owin.Loader.DefaultLoader.Load(string startupName) + 0x13 bytes   
    Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.OwinBuilder.Build() + 0x47 bytes    
    mscorlib.dll!System.Lazy<Microsoft.Owin.Host.SystemWeb.OwinAppContext>.CreateValue() + 0xa5 bytes 
    mscorlib.dll!System.Lazy<Microsoft.Owin.Host.SystemWeb.OwinAppContext>.LazyInitValue() + 0x16f bytes  
    mscorlib.dll!System.Lazy<Microsoft.Owin.Host.SystemWeb.OwinAppContext>.Value.get() + 0x79 bytes   
    Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.OwinApplication.Instance.get() + 0x12 bytes 
    Microsoft.Owin.Host.SystemWeb.dll!Microsoft.Owin.Host.SystemWeb.OwinHttpModule.Init(System.Web.HttpApplication context) + 0x2d bytes    
    System.Web.dll!System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(System.IntPtr appContext, System.Web.HttpContext context, System.Reflection.MethodInfo[] handlers) + 0x1a7 bytes    
    System.Web.dll!System.Web.HttpApplication.InitSpecial(System.Web.HttpApplicationState state, System.Reflection.MethodInfo[] handlers, System.IntPtr appContext, System.Web.HttpContext context) + 0xb8 bytes    
    System.Web.dll!System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(System.IntPtr appContext, System.Web.HttpContext context) + 0x119 bytes  
    System.Web.dll!System.Web.HttpApplicationFactory.GetPipelineApplicationInstance(System.IntPtr appContext, System.Web.HttpContext context) + 0x37 bytes  
    System.Web.dll!System.Web.Hosting.PipelineRuntime.InitializeApplication(System.IntPtr appContext) + 0xab bytes  
    [Appdomain Transition]  
    [Native to Managed Transition]  

원인은 Microsoft.Owin.Host.SystemWeb 어셈블리 때문인데요, 소스 코드는 다음과 같습니다.

internal static OwinAppContext Build()
{
    string str = ConfigurationManager.AppSettings["owin:Configuration"];
    DefaultLoader loader = new DefaultLoader();
    return Build(loader.Load(str ?? string.Empty));
}

public Action<IAppBuilder> Load(string startupName) => 
    (this.LoadImplementation(startupName) ?? this._next(startupName));
        
private Action<IAppBuilder> LoadImplementation(string startupName)
{
    if (string.IsNullOrWhiteSpace(startupName))
    {
        startupName = GetDefaultConfigurationString(assembly => new string[] { "Startup", assembly.GetName().Name + ".Startup" });
    }
    Tuple<Type, string> typeAndMethodNameForConfigurationString = GetTypeAndMethodNameForConfigurationString(startupName);
    if (typeAndMethodNameForConfigurationString == null)
    {
        return null;
    }

    ...
}

GetDefaultConfigurationString 메서드에서 역시 /bin 폴더의 모든 어셈블리를 로드해 보는 것이 문제인데요. 아쉽게도 이를 우회할 수 있는 공식적인 방법은 없습니다. 단지, 위의 소스 코드에서 볼 수 있듯이 Build 메서드에서 "owin:Configuration"의 결과에 따라 GetDefaultConfigurationString 메서드의 수행을 비켜갈 수 있기 때문에 OWIN을 쓰지 않는 경우라면 AppSettings에 다음과 같은 항목을 넣어주면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...[생략]...

    <appSettings>
        <add key="owin:Configuration" value="blah.blah" />

        ...[생략]...
    </appSettings>

    ...[생략]...
</configuration>

value 문자열은 OWIN을 쓰지 않는 경우라면 무엇을 넣어도 상관없습니다. OWIN을 쓰는 경우라면 어떤지 모르겠지만, OWIN을 쓸 상황이라면 아마 대부분 native DLL을 사용하지 않을 것이므로 저런 문제가 발생하지는 않을 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 6/27/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12377정성태10/15/202011354디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208099오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209463Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(&#0165;)' 기호로 나오는 경우 [1]
12374정성태10/14/202014057.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209335.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011288.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/20209973개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202010829Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202013657Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/20209672오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202022430오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202011492.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202010456.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202011664.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202012572.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/20209311VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202010921.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/20208154오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/20209655오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/20209662오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/20207763오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202022418오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/20207839오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202020672오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202010469개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202010978개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...