初始化安装时发生异常:System.BadImageFormatException:无法加载文件或程序集 - c#

我将Worker Services作为Windows服务安装在机器上,但是尝试安装时会出现以下错误

Microsoft (R) .NET Framework Installation utility Version 4.8.3752.0
Copyright (C) Microsoft Corporation.  All rights reserved.

Exception occurred while initializing the installation:
System.BadImageFormatException: Could not load file or assembly 'file:///C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe' or one of its dependencies. The module was expected to contain an assembly manifest..

以下是正在使用的软件包的.csproj文件内容

<Project Sdk="Microsoft.NET.Sdk.Worker">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.1" />
    <PackageReference Include="System.ServiceModel.Duplex" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Http" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.NetTcp" Version="4.4.*" />
    <PackageReference Include="System.ServiceModel.Security" Version="4.4.*" />
  </ItemGroup>

  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
</Project>

在查看程序集绑定日志查看器时,我看到此错误日志。

** Assembly Binder Log Entry  (2/14/2020 @ 1:41:17 PM) ***

The operation failed.
Bind result: hr = 0x80131018. No description available.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: Where-ref bind. Location = C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Appbase = file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = InstallUtil.exe
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:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Attempting download of new URL file:///C:/Users/JNyingi/source/repos/SeSPWS/SeSPWS/bin/Release/netcoreapp3.0/SeSPWS.exe.
LOG: Assembly download was successful. Attempting setup of file: C:\Users\JNyingi\source\repos\SeSPWS\SeSPWS\bin\Release\netcoreapp3.0\SeSPWS.exe
LOG: Entering run-from-source setup phase.
ERR: Error extracting manifest import from file (hr = 0x80131018).
ERR: Run-from-source setup phase failed with hr = 0x80131018.
ERR: Failed to complete setup of assembly (hr = 0x80131018). Probing terminated.

我已经安装了以下运行时; .NET Core 3.0,ASP.NET Core 3.0和Windows桌面3.0。但是,即使升级到.NET Core 3.1运行时,该服务仍然无法安装。

以下是我的构建配置文件

初始化安装时发生异常:System.BadImageFormatException:无法加载文件或程序集 - c#

我建立了一个类似的工作程序服务,安装之前没有任何麻烦。希望我能解决此错误并将服务部署到计算机上。

编辑
以下是我的课程

public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateWebHostBuilder(args).Build().RunAsService();
            }
            else
            {
                CreateWebHostBuilder(args).Build().Run();
            }
        }


        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName))
                .UseStartup<Startup>()
                .UseKestrel((context, serverOptions) =>
                {
                    serverOptions.ListenAnyIP(1042);
                    serverOptions.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1.5);
                });
    }

编辑2
初始化安装时发生异常:System.BadImageFormatException:无法加载文件或程序集 - c#
这些是用于服务的NuGet软件包

参考方案

大多数情况下,该错误是由于Application | Platform | Installutil|IIS的位不兼容引起的

我汇总了您可以执行的各种检查:

主项目Project > Properties > Uncheck Prefer 32 bit的设置
主项目Project > Properties > /platform:AnyCpu的设置或目标(x86) for 32bit的BITness
如果您在项目中引用其他DLL,请确保没有BITness不匹配
验证您的App.Config文件,查看它是否有行,它指定与应用程序目标的目标运行时不同的目标运行时
验证由IIS> AppPool> Enable 32 bit applications设置的位数
取消选中"Use the 64 bit version of IIS Express for Web Sites and Projects"下的Projects and Solutions选项
检查用于安装服务的InstallUtil版本
检查项目的StartUp,看看它是否是预期的
尝试以管理员身份运行InstallUtil(从另一篇文章中可以看到)
从VS Navigate to Visual Studio – Tools – Options – Projects and Solutions – Web Projects取消选中IIS的64位版本
通过查看.CSProj文件验证位数
您可以通过使用FusionLogging或DependencyWalker工具确定导致此异常的程序集来进一步缩小范围,从而能够确定哪个dll在运行时加载失败

进一步阅读:

这篇Medium帖子介绍了在.NetCore中创建Windows服务的过程

编辑:根据OP下的帖子分解根本原因

WebHostBuilder主要允许我们配置和构建WebHost,最适合于Web应用程序。
但是,使用.net core 2.1,引入了新选项“通用”主机,使开发人员能够创建可以运行后台任务,创建服务和处理消息的控制台应用程序。
请参阅Generic Host for Windows Services上的“ Steve Gordons”文章
创建工作人员服务模板时,需要从nuget中引用Microsoft.Extensions.Hosting.WindowsServices
现在,我们可以使用IHostBuilder.UseWindowsService()
有2种使用方式(请参阅下一点):后台工作程序服务(使用Microsoft.Net.Sdk.Worker),Web App(Microsoft.NET.Sdk.Web)服务示例,区别在于Microsoft.Extensions.Hosting包在前一个中被明确引用。
MSDN文章对此进行了解释

<Project Sdk="Microsoft.NET.Sdk.Web">
现在,您可以在这里使用IWebHostBuilder
但是请确保将其用于使用Razor Pages或MVC框架的基于Web应用程序的服务。 A Good example
<Project Sdk="Microsoft.NET.Sdk.Worker">
此类型适合Windows服务创建的大多数需求,其中服务需要执行后台任务

<RuntimeIdentifier>元素与“自包含”部署一起使用,.NET软件包用于表示NuGet软件包中特定于平台的资产

C#无法将类型为“ System.Double”的对象转换为类型为“ System.Single” - c#

在判断此问题已得到回答之前,请阅读说明。我在下面有这个简单的代码:Dictionary<string, object> d = new Dictionary<string, object>(); d.Add("key" , 30d); System.Diagnostics.Debug.WriteLine($…

jQuery不起作用 - php

我正在使用带有ajax的jquery。有时,给出错误$未定义。这是我的代码:<script language="javascript" type="text/javascript"> var base_path="<? echo $this->baseUrl().'/…

Div单击与单选按钮相同吗? - php

有没有一种方法可以使div上的click事件与表单环境中的单选按钮相同?我只希望下面的div提交值,单选按钮很丑代码输出如下:<input id="radio-2011-06-08" value="2011-06-08" type="radio" name="radio_date&#…

在Android Studio中设计可滚动内容时应遵循的方法是什么? - java

我正在约束布局中设计我的应用程序,并将其放置在“滚动视图”下。我想放置更多的Card Views,但是在xml文件的预览中没有放置空间。当布局已满时,我应该在哪里拖放Buttons,TextViews等?我已经处理了文本的滚动视图,但这是另外一回事。我知道我只能输入代码,但是当内容超出定义的屏幕尺寸时,我将无法看到我正在设计的内容时,我将很难这样做。(如果您…

将python scikit学习模型导出到pmml - python

我想将python scikit-learn模型导出到PMML。哪个python软件包最合适?我阅读了有关Augustus的内容,但是我无法使用scikit-learn模型找到任何示例。 python大神给出的解决方案 SkLearn2PMML是 JPMML-SkLearn命令行应用程序周围的薄包装。有关受支持的Scikit-Learn Estimator和…