首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >初始化安装时发生异常: System.BadImageFormatException:未能加载文件或程序集

初始化安装时发生异常: System.BadImageFormatException:未能加载文件或程序集
EN

Stack Overflow用户
提问于 2020-02-15 06:41:25
回答 2查看 3.3K关注 0票数 4

我将Worker Services作为Windows服务安装在一台计算机上,但是当我尝试安装它时,它会抛出以下错误

代码语言:javascript
运行
复制
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文件内容

代码语言:javascript
运行
复制
<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>

当查看程序集绑定日志查看器I时,此错误日志。

代码语言:javascript
运行
复制
** 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 Core3.0、ASP.NET Core3.0和Windows桌面3.0。但是,即使升级到.NET Core3.1运行时,该服务仍然无法安装。

下面是我的构建概要

在此之前,我已经构建了一个类似的工作人员服务,安装之前没有任何匆忙;请解决此错误,并将服务部署到机器上。

下面的编辑是我的程序类

代码语言:javascript
运行
复制
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);
                });
    }

EDIT2

这些是用于服务的NuGet包

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-15 08:34:08

大多数情况下的错误是由于您的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设置的位数
  • 取消选中Projects and Solutions下的Projects and Solutions选项
  • 检查用于安装服务的InstallUtil版本。
  • 检查项目的StartUp,看看它是否是预期的
  • 尝试运行InstallUtil是以管理员身份运行的(从另一篇文章中可以看到)
  • 从VS Navigate to Visual Studio – Tools – Options – Projects and Solutions – Web Projects中取消检查IIS的64位版本
  • 通过查看.CSProj文件验证位数
  • 通过使用FusionLoggingDependencyWalker工具标识导致此异常的程序集,可以进一步缩小范围,您将能够判断哪个dll在运行时加载失败。

继续阅读:

这篇5~6成熟文章解释了在.NetCore中创建Windows的过程

编辑:基于OP下面的文章,分解了根本原因

  • WebHostBuilder主要允许我们配置和构建一个WebHost,并且最适合web应用程序。但是在.net核心2.1中,引入了一个新的选项“generic”主机,使开发人员能够创建能够运行后台任务、创建服务和处理消息的控制台应用程序。参见"Steve“关于Windows服务通用主机的文章
  • 当我们创建工人服务模板时,我们需要一个来自nuget的对Microsoft.Extensions.Hosting.WindowsServices的引用,现在我们可以使用IHostBuilder.UseWindowsService() 有两种方法可以使用这个(请参阅下面的详细信息):后台工作者服务(使用Microsoft.Net.Sdk.Worker),Web (Microsoft.NET.Sdk.Web)服务示例,在前一篇解释这一点的MSDN文章中解释了Microsoft.Extensions.Hosting包的区别。
代码语言:javascript
运行
复制
- `<Project Sdk="Microsoft.NET.Sdk.Web">` Now here you can use IWebHostBuilder But be sure to use this for a web app-based service that uses the Razor Pages or MVC frameworks. [A Good example](https://dzone.com/articles/running-aspnet-core-application-as-windows-service) 
- `<Project Sdk="Microsoft.NET.Sdk.Worker">` This type suits the majority of the requirements for windows service creation where the service needs to executes background tasks

  • <RuntimeIdentifier>元素与自包含的部署一起使用,并被.NET包用来表示NuGet包中特定于平台的资产。
票数 1
EN

Stack Overflow用户

发布于 2020-02-18 05:23:00

因此,在经历了许多令人沮丧的死胡同之后,我们的夫人教我如何解决这个错误。这很简单,我对我的应用程序做了三个主要的修改。

.csproj更新为;

代码语言:javascript
运行
复制
<Project Sdk="Microsoft.NET.Sdk.Worker">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
    <UserSecretsId>dotnet-SeSPWS-00EEA7BA-8CD9-4E72-B073-FB0FB7B9192A</UserSecretsId>
    <ApplicationIcon />
    <OutputType>WinExe</OutputType>
    <StartupObject />
    <RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
    <Platforms>AnyCPU;x64</Platforms>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" />
    <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.Core" Version="2.2.5" />
    <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="Microsoft.Extensions.Hosting.WindowsServices" Version="3.0.0" />
    <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>

我还更改了我的program.cs,并从IWebHostBuilder更改为IHostBuilder,如下所示;

代码语言:javascript
运行
复制
public class Program
    {
        public static void Main(string[] args)
        {
            var isService = !(Debugger.IsAttached || args.Contains("--console"));
            if (isService)
            {
                CreateHostBuilder(args).Build().Run();//.RunAsService();
            }
            else
            {
                CreateHostBuilder(args).Build().Run();
            }
        }


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

为了确保服务使用特定版本的.Net Core SDK构建,我添加了以下global.json

代码语言:javascript
运行
复制
{
  "sdk": {
    "version": "3.0.100",
    "rollForward": "disable"
  }
}

然后我建立并出版了。

注意到:我还注意到InstallUtil不适用于ASP.NET员工服务。因此,您必须更改并使用SC来安装service.Like;

SC {SERVICENAME} binpath="{path-to-exe}"

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60236508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档