將原本運作正常的ASP.NET MVC專案,複製到新的Solution改版開發,出現Visual Studio編譯正常,在IIS Express執行冒出編譯錯誤的狀況:

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Assembly Load Trace: The following information can be helpful to determine why the assembly 'Newtonsoft.Json' could not be loaded.

...省略...

LOG: Using application configuration file: X:\TFS\v4\Afa.WebApi\web.config
LOG: Using host configuration file: X:\Users\jeffrey\Documents\IISExpress\config\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.5.0.0 redirected to 6.0.0.0.
LOG: Post-policy reference: Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed

檢查web.config,安裝Json.NET NuGet套件時已自動加入Redirect將所有版本指向6.0:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
</assemblyBinding>

檢查Visual Studio中的專案參照,發現Newtonsoft.Json跑到Blend的安裝目錄去了,版本還變成4.6!

stackoverflow找到類似案例:原因出在ASP.NET MVC專案被直接複製到新位置,但csproj的Json.NET參照HintPath仍指向原Solution的packages目錄,該相對路徑在搬動後已失效。Visual Studio透過「自己的邏輯」找到替代品-Blend目錄的舊版Json.NET元件,故仍能編譯成功。但此一舊版元件不在IIS Express的搜尋範圍內,於是產生無法載入元件的錯誤。

解決方案,使用文字編輯器開啟csproj,將以下ItemGroup的HintPath指向正確路徑,問題排除!

<ItemGroup>
  <Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
    <SpecificVersion>False</SpecificVersion>
    <HintPath>..\OldFolder\packages\Newtonsoft.Json.6.0.3\lib\net40\Newtonsoft.Json.dll</HintPath>
  </Reference>

PS: 想了解VS找出DLL的邏輯,可調整以下設定,Visual Studio將會為你娓娓道來…


Comments

# by Rico

原來是這樣....其實這個問題困擾我好幾回了,但是我沒找到問題點在這邊。

# by andy

謝謝這篇我才能找到另一個狀況的解法 「Visual Studio keeps overwriting NewtonSoft.Json.DLL with an older version」

Post a comment