在做asp.net MVC 開發時,因為引用的dll 中使用了更高版本的 Newtonsoft.Json ,導致運行時發生錯誤,
查資料說是因為webApi使用了Newtonsoft.Json 導致了,我的項目中沒有用到webapi,因此,在Global.asax 中把 下面這行代碼屏蔽后,果然不再報錯了。
// WebApiConfig.Register(GlobalConfiguration.Configuration);
但是,當我在發布該項目時,又遇到了以下錯誤:
無法解決“Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”與“Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”之間的沖突。正在隨意選擇“Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”。 1> 請考慮使用 app.config 將程序集“Newtonsoft.Json, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed”從版本“4.5.0.0”[D:\Program Files (x86)\Microsoft Visual Studio 12.0\Blend\Newtonsoft.Json.dll]重新映射到版本“7.0.0.0”[E:\project\.....\Debug\Newtonsoft.Json.dll],以解決沖突並消除警告。 1>C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(1635,5): warning MSB3247: 發現同一依賴程序集的不同版本間存在沖突。在 Visual Studio 中,請雙擊此警告(或選擇此警告並按 Enter)以修復沖突;否則,請將以下綁定重定向添加到應用程序配置文件中的“runtime”節點: <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /><bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /></dependentAssembly></assemblyBinding>
雖然該錯誤並沒有影響到程序運行,但是我還是覺得不爽,細看說明,原理微軟在提示我們時,就把解決方法告訴了我們:
否則,請將以下綁定重定向添加到應用程序配置文件中的“runtime”節點: <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /><bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /></dependentAssembly> </assemblyBinding>
意思是,把上面這串xml 代碼放到runtime 節點里,把用到0.0.0.0-7.0.0.0 版本的dll 的地方,全部重新定位到7.0.0.0 版本,因為這個dll基本可以兼容,所以問題得到解決。
推而廣之,其他的dll沖突也可以用這種方式解決。