Visual Studio 2019发布.NET Framework 4.5.1 Web服务时aspnet_compiler.exe退出码1问题
问题背景
在Visual Studio 2019中修改基于.NET Framework 4.5.1的Web服务项目后,项目可正常构建,但发布时触发错误:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\VisualStudio\v16.0\Web\Transform\Microsoft.Web.Publishing.AspNetCompileMerge.targets(462,5): Error MSB6006: "aspnet_compiler.exe" exited with code 1.
后续通过事件查看器排查到深层错误:
Application: csc.exe
Framework Version: v4.0.30319
Description: The application requested process termination through System.Environment.FailFast(string message).
Message: System.IO.FileLoadException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
撤销所有修改后问题仍存在,最终错误指向csc.exe的未处理异常:
Application: csc.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileLoadException
at Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main(System.String[])
解决思路与方案
1. 添加程序集版本重定向
尽管代码未直接引用System.Runtime.CompilerServices.Unsafe,但Visual Studio 2019内置的Roslyn编译组件可能间接依赖该程序集,且存在版本不匹配问题。在项目的web.config中添加绑定重定向:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.4.1" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
注:若本地安装的是更高版本的该程序集,需将newVersion改为对应版本号。
2. 清理并重新还原NuGet包
- 右键项目 → 打开管理NuGet程序包,卸载
System.Runtime.CompilerServices.Unsafe及所有依赖它的包 - 删除项目目录下的
packages、obj、bin文件夹 - 打开Package Manager Console,执行
Update-Package -reinstall重新还原所有包 - 重启Visual Studio后尝试发布
3. 更新Visual Studio的Roslyn组件
该问题可能源于Roslyn编译器与.NET Framework 4.5.1的兼容性冲突:
- 打开Visual Studio Installer,选择修改你的2019 Enterprise版本
- 在单个组件中找到并勾选最新版的
.NET Compiler Platform (Roslyn),完成更新后重启VS
4. 调整发布的预编译配置
- 右键项目 → 进入发布设置页
- 在文件发布选项中,取消勾选预编译发布(若启用),尝试直接发布未编译文件
- 若必须预编译,勾选允许预编译站点可更新,并取消合并所有输出到单个程序集选项
5. 修复Visual Studio 2019
若上述方法无效,可能是VS组件损坏:
- 打开Visual Studio Installer,选择你的2019版本,点击修复,完成后重启VS重新操作
内容的提问来源于stack exchange,提问作者Colin Plater

