c# - 无法加载引用程序集以从网站项目执行

标签 c# asp.net web-site-project .net-standard

使用 .NET 4.6.2 和较旧的网站(而非 Web 应用程序)项目。如果我清除 BIN 目录然后构建并运行它,它会工作,但有时在多次构建和运行之后,它会失败并出现此错误。

Server Error in '/' Application.
Cannot load a reference assembly for execution.
....
[BadImageFormatException: Cannot load a reference assembly for execution.]
[BadImageFormatException: Could not load file or assembly 'netfx.force.conflicts' or 
one of its dependencies. Reference assemblies should not be loaded for execution.  
They can only be loaded in the Reflection-only loader context.
(Exception from HRESULT: 0x80131058)]
....

当网站项目使用的库开始引入 netstandard 2.0 时,是否有任何技巧可以让网站项目正常工作?

另外,似乎这个程序集绑定(bind)重定向是让它运行所必需的,但 nuget 添加了一个指向旧版本 4.1.1.0 的重定向。除了在大多数 nuget 更新后手动编辑此行之外,关于如何修复该问题的任何建议?

  <dependentAssembly>
    <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a"
                      culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0" />
  </dependentAssembly>

如果将项目迁移到 Web 应用程序项目,所有这些问题都会消失吗?

最佳答案

您遇到此错误的原因很可能是 x86 和 x64 编译程序集之间不匹配,或者类似地,.NET Framework 和 .NET Core 之间不匹配。

这里有一些您可能没有尝试过的故障排除选项。

选项#1

AppDomain 中,有一个事件处理程序用于程序尝试解析引用的程序集。如果您订阅它,您应该能够获得有关缺少内容的更多信息。这是实现的样子:

AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

事件处理器:

private System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    System.Diagnostics.Trace.TraceInformation($"Trying to resolve assebly: {args.Name} requested by {args.RequestingAssembly.FullName}");
    // This event handler allows you to help the find the assembly for the CLR.
    // you can dynamically load the assembly and provide it here. 
    return null;
}

选项#2

.NET SDK 中还有一个用于解决绑定(bind)问题的工具。

这里是关于 Assembly Binding Log Viewer 的更多信息

您需要在它发出任何有趣的信息之前启用它,但是如果 AssemblyResolve 事件没有帮助,这应该可以让您找到问题的根源。

关于c# - 无法加载引用程序集以从网站项目执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45968898/

相关文章:

c# - 如何在 C# 中通过用户交互运行注册表文件

c# - 枚举 EF 5.0 - 数据库优先

c# - ASP.NET 5 (vNext) - 配置

c# - 使用 msbuild 从网站部署中排除文件

c# - 如何在 C# 中将 Dictionary<> 转换为 Hashtable?

c# - C#NEST ElasticSearch搜索并突出显示所有类型的所有字段

asp.net - 在负载平衡环境中覆盖 HttpContext.Current.Cache。

c# - 解密在 ASP.NET 之外的 web.config 文件中使用 RsaProtectedConfigurationProvider 完成的加密

ASP.NET 网站与 Web 应用程序