WCF 服务 BadImageFormatException

WCF Service BadImageFormatException

我刚刚创建了一个 wcf 服务库,并且正在使用一个简单的控制台应用程序连接到它。然而,当我启动我的控制台应用程序时,wcf 服务主机打开并显示此错误:

System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\uop\source\repos\WPF\APPONE\APPONE.Service\bin\x86\Debug\APPONE.Service.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.
File name: 'file:///C:\Users\amosa\source\repos\WPF\APPONE\APPONE.Service\bin\x86\Debug\APPONE.Service.dll'
   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.Assembly.Load(AssemblyName assemblyRef)
   at Microsoft.Tools.SvcHost.ServiceHostHelper.LoadServiceAssembly(String svcAssemblyPath)

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].

我已确保我所有的应用程序都是 运行 x86。

我试图查看它是否是我程序中的问题,但它甚至没有到达我程序中的第一个调试点:

static void Main(string[] args)
{
    // Step 1: Create a URI to serve as the base address.
    Uri baseAddress = new Uri("http://localhost:8733/APPONE/");

    // Step 2: Create a ServiceHost instance.
    ServiceHost selfHost = new ServiceHost(typeof(DocumentType), baseAddress);

    try
    {
        selfHost.AddServiceEndpoint(typeof(IDocumentType), new WSHttpBinding(), "DocumentType");
        // Step 4: Enable metadata exchange.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        selfHost.Description.Behaviors.Add(smb);

        // Step 5: Start the service.
        selfHost.Open();
        Console.WriteLine("The service is ready.");

        // Close the ServiceHost to stop the service.
        Console.WriteLine("Press <Enter> to terminate the service.");
        Console.WriteLine();
        Console.ReadLine();
        selfHost.Close();

    }
    catch(Exception e)
    {
        Console.WriteLine("An exception occurred: {0}", e.Message);
        selfHost.Abort();
    }
}

根据你的描述,我做了test.First,你需要将平台目标值设置为"Any CPU":

然后将您的项目构建为可执行文件并运行它作为管理员:

另外,我用的.Net framework是4.7的。2.In其实如果你用x86在VS里调试,会出现上面的错误,你直接build工程成可执行文件,然后运行它作为管理员,就可以了。