.NET 5项目dotnet publish -o输出Newtonsoft.Json版本不符问题求助
解决方案
步骤1:排查传递依赖来源
运行以下命令查看当前项目所有传递依赖的Newtonsoft.Json版本,确认是哪个包引入了9.0.0.0的低版本:
dotnet list package --include-transitive | findstr Newtonsoft.Json
步骤2:排除低版本传递依赖
找到引入低版本Newtonsoft.Json的包后,在对应的PackageReference节点中添加排除规则,强制使用你显式引用的13.0.1版本,示例如下(以Newtonsoft.Json.Bson为例):
<PackageReference Include="Newtonsoft.Json.Bson" Version="1.0.2" Exclude="Newtonsoft.Json" />
步骤3:添加强制绑定重定向
在项目.csproj文件的PropertyGroup节点中添加以下配置,强制生成绑定重定向规则:
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
如果上述配置不生效,可以手动在项目根目录添加app.config文件,写入以下绑定规则:
<configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-13.0.0.1" newVersion="13.0.0.1" /> </dependentAssembly> </assemblyBinding> </runtime> </configuration>
步骤4:清理缓存并重新发布
发布前先清空目标输出目录,避免旧文件残留,再执行完整的发布流程:
dotnet clean dotnet restore dotnet publish -o [你的输出目录路径]
备选兜底方案
如果以上方案都不生效,可以在.csproj文件中添加自动复制逻辑,发布时直接将正确版本的dll复制到输出目录,无需手动操作:
<Target Name="ForceCopyNewtonsoftJson" AfterTargets="Publish"> <Copy SourceFiles="$(NugetPackageRoot)newtonsoft.json\13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll" DestinationFolder="$(PublishDir)" OverwriteReadOnlyFiles="true" /> </Target>
内容的提问来源于stack exchange,提问作者Nathan G-T
相关产品推荐
相关产品推荐

