.NET 8生产环境无法加载System.Text.Json程序集,本地运行正常
错误原因及解决方案
核心原因:NuGet包版本冲突
你的项目目标框架是.NET 8,但引用了多个9.0.4版本的NuGet包(Microsoft.Windows.Compatibility、System.Configuration.ConfigurationManager等),这些包依赖于.NET 9版本的System.Text.Json(9.0.0.0)。而你手动指定了System.Text.Json为8.0.0版本,导致程序运行时出现版本不匹配:生产环境中程序尝试加载9.0.0.0版本的System.Text.Json,但部署包中只有8.0版本的文件,因此抛出FileNotFoundException。
本地开发环境能正常运行,是因为.NET SDK的全局缓存或自动版本绑定机制帮你处理了版本冲突,但打包部署到生产环境时,这些自动处理逻辑没有生效。
解决方案
1. 统一NuGet包版本(优先推荐)
将所有9.0.4版本的包降级到与.NET 8兼容的8.x版本,修改.csproj中的对应包引用:
<PackageReference Include="Microsoft.Windows.Compatibility" Version="8.0.0" /> <PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" /> <PackageReference Include="System.Diagnostics.PerformanceCounter" Version="8.0.0" /> <PackageReference Include="System.ServiceProcess.ServiceController" Version="8.0.0" />
修改后执行以下命令清理、还原并重新编译:
dotnet clean dotnet restore dotnet build
重新打包部署,确保所有依赖版本与.NET 8一致。
2. 添加版本绑定重定向(临时 workaround)
如果无法降级包,可通过绑定重定向让程序将对9.0.0.0版本System.Text.Json的请求定向到8.0.0.0版本:
- 在项目中添加
app.config文件,内容如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="8.0.0.0" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
- 在
.csproj中添加该文件的复制配置:
<ItemGroup> <None Update="app.config"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup>
确保打包时该文件随程序一起部署。
3. 验证打包完整性
检查生产环境的部署目录,确认System.Text.Json.dll(8.0版本)是否存在。如果使用TopShelf打包,需确认打包过程中包含了所有依赖的NuGet包文件。
内容的提问来源于stack exchange,提问作者Mead Ahmed Fahim
相关产品推荐
相关产品推荐

