c# - Native Assembly Binding fails for ASP.NET解决方案

标签 c# asp.net clr

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

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

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

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

How the Runtime Locates Assemblies
Best Practices for Assembly Loading

根据我的理解,我们应该能够加载程序集,但是没有。我收到程序集绑定(bind)错误。

设置

调用 native dll 的我的帮助程序库(编译为 MSIL(任何 CPU))已命名并在 GAC 中。。我在 IIS 上的 Win 7 x64 位机器上运行我的 asp.net 应用程序,而不是 visual studio 开发服务器。 nativedll 未签名且未通过 GAC。

问题
总结是,当我将 native dll 放在 windows 目录中时,(c:\Windows) 解决方案工作正常。在任何其他情况下,我都会收到程序集绑定(bind)错误。

问题
1.我想知道为什么程序集在windows目录下会被绑定(bind)? 2. error: ERR: Error extracting manifest import from file (hr = 0x80131018) 是什么意思? (看场景一,场景六)
3.为什么调用Assembly.Load*()方法会失败? (场景 3、4、5)

我的测试结果

场景 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.

最佳答案

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

/bin 文件夹中的 .NET 程序集在网站启动时由 ASP.NET 自动加载,但不会加载任何 native 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>

关于c# - Native Assembly Binding fails for ASP.NET解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13869621/

相关文章:

asp.net - 创建动态数量的 GridView

c++ - 如何修复 C++ winforms 应用程序中的 _CrtIValidHeapPoint(pUserData) 断言失败

c# - C# 中的替换方法不适用于单个字符?

c# - 如何在 ServiceStack 中启用 swagger?

asp.net - Episerver CMS 6 页面加载速度慢

visual-studio-2010 - 禁止在 VS2010 中生成 metagen 文件

c# - C# 中的 fork 概念

c# - XElement 获取所有子元素节点名称和值

c# - AuthCookie 已设置,仍被重定向到 login.aspx

jquery - 如何通过 JQuery AJAX ASP.NET 发送空数据