.NET 4.8应用引用Newtonsoft.Json版本不匹配加载失败求助
问题描述
在.NET 4.8应用里使用Newtonsoft.Json时碰到版本不匹配问题,试了网上各种app.config配置方案都没用。报错内容如下:
System.IO.FileLoadException HResult=0x80131040 Message=Could not load file or assembly 'Newtonsoft.Json, Version=13.0.3.27908, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040) Source=TRFBusServiceProxies StackTrace: at TRFBusServiceProxies.CRD.LMECRDAPIClient.<GetAllMembers>d__4.MoveNext() at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine) at TRFBusServiceProxies.CRD.LMECRDAPIClient.GetAllMembers() at TRFBusServiceAgents.LMECRDClient.<GetAllMembers>d__7.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at TRFBusServiceAgents.Tests.BusServiceAgentModuleTests.<CRDRetrieval_GetAllMembers>d__16.MoveNext() in C:\Development\trfbusserviceagents\TRFBusServiceAgentsSolution\TRFBusServiceAgents.Tests\BusServiceAgentModule.Tests.cs:line 285 Inner Exception 1: FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
已确认本地DLL文件版本为13.0.3.27908,但app.config配置始终未解决问题。
解决方案
1. 配置正确的程序集绑定重定向
直接在app.config的<runtime>节点下添加以下规则,将所有对13.0.0.0及以下版本的请求重定向到13.0.3.27908:
<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.0" newVersion="13.0.3.27908" /> </dependentAssembly> </assemblyBinding> </runtime>
注意:如果是测试项目报错,测试项目的app.config也需要添加相同配置。
2. 统一解决方案内所有项目的NuGet版本
- 右键解决方案→管理解决方案的NuGet程序包,找到Newtonsoft.Json,将所有项目的版本统一设置为13.0.3,避免跨项目版本不一致。
- 清理NuGet缓存,在命令行执行:
之后右键解决方案→还原NuGet程序包,确保所有项目引用的是同一版本的DLL。nuget locals all -clear
3. 清理输出目录并重新编译
- 删除所有项目的
bin和obj文件夹,防止旧版本DLL残留。 - 重新生成整个解决方案,编译完成后检查输出目录中的Newtonsoft.Json.dll版本是否为13.0.3.27908。
4. 排查第三方依赖的版本冲突
报错来源为TRFBusServiceProxies项目,需检查该项目引用的第三方组件是否依赖Newtonsoft.Json 13.0.0.0:
- 打开该项目的
packages.config或.csproj文件,查看是否存在间接引用旧版本的情况。 - 如果第三方组件有更新版本,尝试升级至兼容Newtonsoft.Json 13.0.3的版本。
5. 使用绑定日志定位根源
运行fuslogvw.exe(程序集绑定日志查看器),详细追踪程序集加载过程:
- 以管理员身份打开Visual Studio命令提示符,输入
fuslogvw.exe启动工具。 - 点击「设置」,选择「记录所有绑定失败到磁盘」并指定日志目录。
- 运行报错的测试或程序,回到工具查看绑定失败的详细日志,定位哪个模块在请求旧版本的Newtonsoft.Json及加载路径,针对性解决问题。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

