ASP.NET 解决方案的本机程序集绑定失败

Posted

技术标签:

【中文标题】ASP.NET 解决方案的本机程序集绑定失败【英文标题】:Native Assembly Binding fails for ASP.NET solution 【发布时间】:2012-12-13 22:28:23 【问题描述】:

注意:此问题的主要目的是了解/解释 CLR 的程序集绑定行为。一旦确定了原因,解决方案应该是显而易见的。请知道,我了解我的设置不是最佳的(nativedll 未签名和版本控制等),但我再次只想调查 CLR 的绑定行为。

我正在尝试在我的 asp.net 解决方案中使用本机(非 COM、C++)dll。我将避免命名 dll,因为我认为它会将主题转移到错误的方向。

本机 dll 来自博客站点,并没有太多信息。我没有任何关于原生 dll 的信息,比如编译它的架构、它是什么文化和版本等。使用提供的包装器,我可以在控制台应用程序中正确使用 dll。即使我们必须使用 部分程序集名称 进行绑定,它仍然有效。本机程序集的包装器具有 DLL 导入,例如 [DllImport("nativedll.dll")] public static extern void someMethod([Out] BE_VERSION pbeVersion);

我已经阅读了大量有关 CLR 程序集绑定的信息,包括:

How the Runtime Locates AssembliesBest Practices for Assembly Loading

根据我的理解,我们应该能够加载程序集,但不能。我收到程序集绑定错误。 设置 我调用本机 dll 的帮助程序库(编译为 MSIL(任何 CPU))是强命名的,并且在 GAC 中。。我在 IIS 上的 Win 7 x64 位机器上运行我的 asp.net 应用程序,而不是 Visual Studio 开发服务器。 nativedll 未签名且未经过 GAC。

问题 总结是,当我将本机 dll 放在 windows 目录中时,(c:\Windows) 解决方案工作正常。在任何其他情况下,我都会遇到程序集绑定错误。 问题 1.我想知道为什么程序集在windows目录下会被绑定? 2. 错误是什么意思:ERR: Error extracting manifest import from file (hr = 0x80131018)? (看场景一、场景六) 3. 为什么调用 Assembly.Load*() 方法会失败? (场景三、四、五)

我的测试结果场景 1:

**Setup**
Calling Assembly: GACed.
Native Assembly: Included in project; Build Action: None; Copy To Output Directory: Copy Always.

**Description:** 
Logged into the site, home page open. Did not navigate to the page with native call.

**Result:** 
    Binding Error
    *** Assembly Binder Log Entry  (12/13/2012 @ 11:28:23 AM) ***

        The operation failed.
        Bind result: hr = 0x80131018. No description available.

        Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
        Running under executable  C:\Windows\SysWOW64\inetsrv\w3wp.exe
        --- A detailed error log follows. 

        === Pre-bind state information ===
        LOG: User = NT AUTHORITY\SYSTEM
        LOG: DisplayName = nativedll
         (Partial)
        WRN: Partial binding information was supplied for an assembly:
        WRN: Assembly Name: nativedll | 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.
        LOG: Appbase = file:///C:/WebUI/
        LOG: Initial PrivatePath = C:\WebUI\bin
        LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: AppName = ca4be085
        Calling assembly : (Unknown).
        ===
        LOG: This bind starts in default load context.
        LOG: Using application configuration file: C:\WebUI\web.config
        LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
        LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
        LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/WebUI/bin/nativedll.DLL.
        LOG: Assembly download was successful. Attempting setup of file: C:\WebUI\bin\nativedll.dll
        LOG: Entering download cache setup phase.
        ERR: Error extracting manifest import from file (hr = 0x80131018).
        ERR: Setup failed with hr = 0x80131018.
        ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.    

场景 2:

**Setup**
Scenario 1 + Just copy the nativedll to C:\Windows folder. No reset of anytype. 

**Description**
Navigate to the page calling native.

Result: 
Success. Native Functionality is invoked. No binding failure.

场景 3:

**Setup**
Calling Assembly: GACed.
Native Assembly: Build Action: None; Copy To Output Directory: Copy Always.

Description: 
    Breakpoint at the point of native function call, use immediate window to execute the following code:

        var pat = pat = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "nativedll.dll");
        var a = Assembly.LoadFrom(pat);

    **Result**
    Exception raised:

    System.BadImageFormatException was unhandled
      HResult=-2146234344
      Message=Could not load file or assembly 'file:///C:\WebUI\bin\nativedll.dll' or one of its dependencies. The module was expected to contain an assembly manifest.
      Source=mscorlib
      FileName=file:///C:\WebUI\bin\nativedll.dll
      FusionLog=Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
        Running under executable  C:\Windows\SysWOW64\inetsrv\w3wp.exe
        --- A detailed error log follows. 

        === Pre-bind state information ===
        LOG: User = NT AUTHORITY\SYSTEM
        LOG: Where-ref bind. Location = C:\WebUI\bin\nativedll.dll
        LOG: Appbase = file:///C:/WebUI/
        LOG: Initial PrivatePath = C:\WebUI\bin
        Calling assembly : (Unknown).
        ===
        LOG: This bind starts in LoadFrom load context.
        WRN: Native image will not be probed in LoadFrom context. Native image will only be probed in default load context, like with Assembly.Load().
        LOG: Using application configuration file: C:\WebUI\web.config
        LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\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:///C:/WebUI/bin/nativedll.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)
               at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
               at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
               at System.Reflection.Assembly.LoadFrom(String assemblyFile)
          InnerException: 

场景 4:

**Setup**
    Calling Assembly: GACed.
    Native Assembly: Build Action: None; Copy To Output Directory: Copy Always.

**Description** 
    Breakpoint at the point of native function call, use immediate window to execute the following code:

    var pat = pat = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "nativedll.dll");
    var a = Assembly.Load(pat);

**Result**
    Exception raised:

        System.IO.FileLoadException was unhandled
          HResult=-2146234297
          Message=Could not load file or assembly 'C:\\WebUI\\bin\\nativedll.dll' or one of its dependencies. The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
          Source=mscorlib
          FileName=C:\\WebUI\\bin\\nativedll.dll
          FusionLog=""
          StackTrace:
               at System.Reflection.AssemblyName.nInit(RuntimeAssembly& assembly, Boolean forIntrospection, Boolean raiseResolveEvent)
               at System.Reflection.RuntimeAssembly.CreateAssemblyName(String assemblyString, Boolean forIntrospection, RuntimeAssembly& assemblyFromResolveEvent)
               at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
               at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
               at System.Reflection.Assembly.Load(String assemblyString)
          InnerException: 

场景 5:

**Setup**
Calling Assembly: GACed.
Native Assembly: Build Action: None; Copy To Output Directory: Copy Always.

**Description: **
    Breakpoint at the point of native function call, use immediate window to execute the following code:

    var pat = pat = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "nativedll.dll");
    var a = Assembly.LoadFile(pat);

    **Result**
    Exception raised:

        System.BadImageFormatException was unhandled
          HResult=-2146234344
          Message=The module was expected to contain an assembly manifest. (Exception from HRESULT: 0x80131018)
          Source=mscorlib
          StackTrace:
               at System.Reflection.RuntimeAssembly.nLoadFile(String path, Evidence evidence)
               at System.Reflection.Assembly.LoadFile(String path)
          InnerException: 

场景 6:

**Setup**
Calling Assembly: GACed.
Native Assembly: Excluded from project. Manually copied into the bin folder prior to execution.

**Description: **
    Logged into the site, home page open. Did not navigate to the page with native call.

    **Result**
    Binding Error: (Output: Assembly Binding Log Viewer)

        Assembly Binder Log Entry  (12/13/2012 @ 2:19:13 PM)

        The operation failed.
        Bind result: hr = 0x80131018. No description available.

        Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
        Running under executable  C:\Windows\SysWOW64\inetsrv\w3wp.exe
        --- A detailed error log follows. 

        === Pre-bind state information ===
        LOG: User = NT AUTHORITY\SYSTEM
        LOG: DisplayName = nativedll
         (Partial)
        WRN: Partial binding information was supplied for an assembly:
        WRN: Assembly Name: nativedll | 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.
        LOG: Appbase = file:///C:/Web/WebUI/
        LOG: Initial PrivatePath = C:\WebUI\bin
        LOG: Dynamic Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: Cache Base = C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\webui\69d9ded4
        LOG: AppName = ca4be085
        Calling assembly : (Unknown).
        ===
        LOG: This bind starts in default load context.
        LOG: Using application configuration file: C:\WebUI\web.config
        LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
        LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
        LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/webui/69d9ded4/ca4be085/nativedll/nativedll.DLL.
        LOG: Attempting download of new URL file:///C:/WebUI/bin/nativedll.DLL.
        LOG: Assembly download was successful. Attempting setup of file: C:\\WebUI\bin\nativedll.dll
        LOG: Entering download cache setup phase.
        ERR: Error extracting manifest import from file (hr = 0x80131018).
        ERR: Setup failed with hr = 0x80131018.
        ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

场景 7:

**Setup**
Scenario 6 + Just copy the nativedll to C:\Windows folder. No reset of anytype. 

**Description**
Navigate to the page calling native.

Result: 
Success. Native Functionality is invoked. No binding failure.

【问题讨论】:

我建议您进入 Assembly.Load 并调试 .NET 框架代码。您可以使用此链接开始msdn.microsoft.com/en-us/library/cc667410.aspx 有几个人指责他们的防病毒软件。 ***.com/questions/11654193/…msmvps.com/blogs/carlosq/archive/2007/03/23/… 【参考方案1】:

据我所知并有相当多的假设......

/bin 文件夹中的 .NET 程序集在网站启动时由 ASP.NET 自动加载,但不会加载任何本机 win32 DLL。

DLLImport 失败,因为 DllImport 是相对于 w3wp.exe 进程而不是相对于网站项目完成的。 AppPool 可以在多个网站之间共享,因此您网站的 /bin 文件夹不能成为 w3wp.exe 进程的 CurrentDirectory,即使这样做不存在安全问题。

因此,为了找到 DLL,IIS 首先在“w3wp.exe”所在的文件夹中查找,然后检查 Windows 系统文件夹。

理论上,您应该能够使用 LoadLibrary() 和 GetProcAddress() 从特定文件夹加载 DLL。

顺便说一句,如果您在网站项目中定义的类中使用 DllImport(),您可能需要将 ASP.NET 的默认编译模式更改为“安全”。要允许使用不安全的代码,您可以更新您的 web.config 文件:

<system.codedom>
    <compilers>
       <compiler ... compilerOptions="/unsafe" >
    </compilers>
</system.codedom>

【讨论】:

您的解释似乎合乎逻辑。我会在时间允许的情况下尽快验证并接受您的回答。非常感谢您的努力。 fuslog 输出清楚地指出找到了目标 dll,只是缺少 dll 中的“预期”清单。所以我认为这与您提到的任何路径错误无关。

以上是关于ASP.NET 解决方案的本机程序集绑定失败的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET运行时错误:未能加载文件或程序集或它的某一依赖项.参数错误.

Asp.Net MVC WebApi CORS 请求失败 - 没有建议的解决方案影响结果

ASP .NET CORE 找不到带有自定义程序集的文件或程序集

如何将 ASP.NET FormView 绑定到单个记录?

请问asp.net dll 编译时 找不到类型或命名空间名称“名称”(是不是缺少 using 指令或程序集引用你如何解决了

ASP.NET Core MVC 项目无法加载程序集