WCF 32位程序调试报错

报错

未能加载文件或程序集“XXXXXX”或它的某一个依赖项。试图加载格式不正确的程序。

实际上是因为引用了32位的类库,故将WCF项目生成的目标平台改为32位(x86),然后启动调试时报错:

System.BadImageFormatException: 未能加载文件或程序集“”或它的某一个依赖项。试图加载格式不正确的程序。
文件名:“”
   在 System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   在 System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   在 System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   在 System.Reflection.Assembly.Load(AssemblyName assemblyRef)
   在 Microsoft.Tools.SvcHost.ServiceHostHelper.LoadServiceAssembly(String svcAssemblyPath)

=== 预绑定状态信息 ===
日志: Where-ref 绑定。位置 = 
日志: Appbase = 
日志: 初始 PrivatePath = NULL
调用程序集: (Unknown)。
===
日志: 此绑定从 LoadFrom 加载上下文开始。
警告: 将不在 LoadFrom 上下文中探测本机映像。仅在默认加载上下文中探测本机映像,例如,使用 Assembly.Load()。
日志: 正在使用应用程序配置文件:
日志: 使用主机配置文件: 
日志: 使用 C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config 的计算机配置文件。
日志: 尝试下载新的 URL 。
错误: 未能完成程序集的安装(hr = 0x8007000b)。探测终止。

查资料知道,VS使用WcfSvcHost.exeWcfTestClient.exe实现WCF类库的托管,而默认的WcfSvcHost.exe和WcfTestClient.exe是64位的(随电脑位数),所以64位的WcfSvcHost.exe和WcfTestClient.exe无法托管32位的WCF类库。
解决这个问题有两种方式:
1.自托管WCF类库,不使用VS提供的工具
参考资料
2.将VS的WcfSvcHost.exe和WcfTestClient.exe改为32位的
WcfSvcHost.exe和WcfTestClient.exe在C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE(类似目录)下
(1)先备份64位的WcfSvcHost.exeWcfTestClient.exe,以便日后切换回64位(当然也可以通过类似下面的命令切换回来)
(2)打开VS的Command Prompt(一种打开方式是在VS->Tool->Command Line->Developer Command Prompt)
(3)执行下面的命令

cd C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE
corflags /32BIT+ /FORCE WcfSvcHost.exe
corflags /32BIT+ /FORCE WcfTestClient.exe

参考资料

How do I compile a WCF Service Library in 32-bit mode?
Debugging a WCF Service Using a 32 Bit Dll

posted @ 2020-10-28 18:47  Lulus  阅读(424)  评论(0编辑  收藏  举报