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

2024-05-15

NOTE:这个问题的主要目的是理解/解释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 程序集绑定的信息,包括:

运行时如何定位程序集 http://msdn.microsoft.com/en-us/library/yx7xezcf(v=vs.100).aspx
程序集加载的最佳实践 http://msdn.microsoft.com/en-us/library/dd153782.aspx

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

SETUP

我的调用本机 dll 的帮助程序库(编译为 MSIL(任何 CPU))是强大的名字并且在 GAC 中。。我在 IIS 上的 Win 7 x64 位机器上运行我的 asp.net 应用程序,而不是 Visual Studio 开发服务器。本机 dll 未签名且未面对。

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

问题

  1. 我想知道为什么程序集放在 windows 目录中时会被绑定?
  2. 错误:ERR:从文件中提取清单导入时出错(hr = 0x80131018)是什么意思? (看场景一、场景六)
  3. 为什么调用 Assembly.Load*() 方法失败? (场景3、4、5)

我的测试结果

场景一:

**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: 

场景四:

**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: 

场景六:

**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.
        

场景七:

**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 自动加载,但不会加载任何本机 win32 DLL。

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

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

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

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

<system.codedom>
    <compilers>
       <compiler ... compilerOptions="/unsafe" >
    </compilers>
</system.codedom>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • 使用 Apache HttpComponents 进行带有 NTLM 身份验证的 http 请求

    快速背景 CFHTTP 不支持 Windows NTLM Authenticate 身份验证 仅支持基本身份验证 我需要发出必须针对 NTLM 进行身份验证的 http 请求 因此我最终推出了自己的 CFHTTP 版本 I found 特里
  • 如何让我的云代码在我的 Worker dyno(而不是 Web dyno)上运行?

    我在heroku 上部署了一个解析服务器 我正在解析服务器上运行一些云代码 该代码需要几分钟才能运行 并且在 Web dyno 上运行时会导致 Heroku 出现超时错误 heroku router at error code H12 de
  • AppDelegate 的变量用作全局变量不起作用

    我想使用我的 AppDelegate 来存储任何其他类都可以访问的对象 我已经像这样声明了这个 AppDelegate interface MyAppDelegate UIResponder
  • angular.js ui + bootstrap typeahead + 异步调用

    我将 typeahead 与 angular js 指令一起使用 但填充自动完成的函数进行了异步调用 我无法返回它来填充自动完成 有没有办法让它与这个异步调用一起工作 我可以假设您正在使用 Bootstrap 2 x 的 typeahead
  • 如何使用 PyQt 抓取桌面截图?

    我可以使用 PyQt 从桌面或任何窗口截取屏幕截图吗 如何处理桌面上的keyPressEvent Thanks 如何截取桌面屏幕截图的示例 import sys from PyQt4 QtGui import QPixmap QApplic
  • 你可以有多个 $(document).ready(function(){ ... });部分?

    如果我在启动时有很多功能 它们都必须在一个功能下 document ready function 或者我可以有多个这样的语句吗 您可以拥有多个 但这并不总是最好的做法 尽量不要过度使用它们 因为这会严重影响可读性 除此之外 这是完全合法的
  • 在 Android 中从麦克风录制 wav 文件 - 问题

    我需要能够使用 Android 中的麦克风创建 WAV 文件 目前 我遇到了很多麻烦 到目前为止 这就是我的情况 我正在使用 micDroid 项目代码的一部分来记录 read thread int sampleRate 44100 int
  • 如何从 Vector 创建非消耗迭代器

    情况 我有一种情况 我想调用定义在Iterator函数参数的特征 我想调用它的函数接受一个类型的参数 该类型是trait called VecLike 该函数称为get all matching rules get all matching
  • php 邮件特殊字符 utf8

    我有以下脚本 在电子邮件中 主题 Testmail Special Characters Body Hi there this isn t somet
  • 无法在 ASP.NET Core 项目中添加对 .NET Core 类库的引用

    我创建了一个新的ASP NET CoreVS 2015 更新 3 中的项目和类库 就是这样project json好像 version 1 0 0 dependencies NETStandard Library 1 6 0 framewo
  • grails 重写重定向控制器方法

    我试图覆盖默认的控制器重定向方法 但似乎无法让以下代码正常工作 我创建了一个插件 我正在尝试使用 doWithDynamicMethods 来替换重定向 def doWithDynamicMethods ctx gt application
  • Java:枚举:NoClassDefFoundError

    我在 J2EE 应用程序中使用枚举时遇到问题 我在无状态服务 bean 内的 switch case 中使用枚举 在运行时 我在 switch 语句上看到以下异常 Caused by java lang NoClassDefFoundErr
  • GCM 无法唤醒设备

    我正在开发 GCM 应用程序 当设备不空闲时 即按电源按钮休眠 一切正常 但是 当我在设备空闲时发送消息时 设备不会唤醒 我做了以下事情 已验证服务器应用程序中的delay while idle未设置为true 每条消息使用不同的折叠键 多
  • virtualenv:指定在系统范围内使用哪些包与在本地使用哪些包[重复]

    这个问题在这里已经有答案了 可能的重复 使 virtualenv 继承全局站点包中的特定包 https stackoverflow com questions 12079607 make virtualenv inherit specifi
  • 获取telegram群组的所有用户

    我正在尝试获取电报组的所有用户 我看到方法 getChatAdministrators 但我认为 API 没有获取所有成员的方法 我正在使用nodejs的telegram bot api Telegram 机器人 API https cor
  • 将 Pytorch LSTM 的状态参数转换为 Keras LSTM

    我试图将现有的经过训练的 PyTorch 模型移植到 Keras 中 在移植过程中 我陷入了LSTM层 LSTM 网络的 Keras 实现似乎具有三种状态类型的状态矩阵 而 Pytorch 实现则具有四种状态矩阵 例如 对于hidden l
  • Eclipse 在处理 xml(传入或传出)时挂起。此时CPU+磁盘尖峰

    我每天必须处理许多 XML 这极大地打断了我的工作流程 我尝试降级到 Indigo 但所有附加组件都被删除 打开xml时出现问题 切换到 xml 切换出一个 xml 甚至切换到另一个 xml 到底发生了什么事情让 XML 如此烦人 我可以禁
  • 将数据从一个线程传递到另一个线程的最快可能方法

    我正在使用增强spsc queue将我的东西从一个线程移动到另一个线程 这是我的软件中的关键位置之一 所以我想尽快完成它 我写了这个测试程序 include
  • 属性错误:“列表”对象没有属性“拆分”

    我正在尝试读取一个文件并用逗号分隔每行中的一个单元格 然后仅显示第一个和第二个单元格 其中包含有关纬度和经度的信息 这是文件 time 纬度 经度 类型2015 03 20T10 20 35 890Z 38 8221664 122 7649
  • ASP.NET 解决方案的本机程序集绑定失败

    NOTE 这个问题的主要目的是理解 解释CLR 的程序集绑定行为 一旦确定原因 解决方案就应该显而易见 请注意 我知道我的设置不是最佳的 nativedll 未签名和版本控制等 但我只是想调查 CLR 的绑定行为 我正在尝试在我的 asp