You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:.NET6运行时加载System.Text.Json依赖失败问题

.NET 6 中央包管理下 System.Text.Json 7.0.0 加载失败问题解决

问题背景

  • 解决方案采用中央包管理,目标框架为.NET 6.0
  • 执行ProjectB时抛出异常:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Text.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot find the file specified.'

依赖关系

  • ProjectA -> library -> System.Net.Http.Json 7.0.1 -> System.Text.Json 7.0.2
  • ProjectB -> ProjectReference 指向 ProjectA
  • ProjectB -> Azure.Monitor.Injestion (1.1.1) -> System.Text.Json 7.0.2

已尝试无效操作

  • 在ProjectB中使用<PackageReference Include="System.Text.Json" VersionOverride="7.0.0" />,未解决问题
  • 拒绝通过降级库获取System.Text.Json 7.0.0版本

解决方案

1. 配置程序集绑定重定向

在ProjectB的App.config(控制台/桌面应用)或Web.config(Web应用)中添加绑定重定向,将7.0.0.0版本的请求导向已安装的7.0.2版本:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="7.0.0.0" newVersion="7.0.2.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

2. 中央包管理强制统一版本

在解决方案根目录的Directory.Packages.props中,直接指定System.Text.Json的版本,确保所有依赖项目统一使用7.0.2:

<Project>
  <PropertyGroup>
    <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
  </PropertyGroup>
  <ItemGroup>
    <PackageVersion Include="System.Text.Json" Version="7.0.2" />
    <!-- 其他包版本配置 -->
  </ItemGroup>
</Project>

此配置会覆盖所有子项目的依赖版本,避免版本分歧。

3. 清理重建并验证输出文件

  • 执行命令清理解决方案:dotnet clean
  • 重新构建:dotnet build
  • 检查ProjectB输出目录(如bin/Debug/net6.0),确认存在System.Text.Json.dll且版本为7.0.2.0
  • 若文件缺失,手动从NuGet包目录(通常为~/.nuget/packages/system.text.json/7.0.2/lib/net6.0)复制到输出目录

4. 单文件发布场景的特殊处理

如果ProjectB发布为单文件应用,需在项目文件中确保System.Text.Json被正确嵌入:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <PublishSingleFile>true</PublishSingleFile>
    <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="System.Text.Json" Version="7.0.2" />
  </ItemGroup>
</Project>

内容的提问来源于stack exchange,提问作者dax78

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:22:46