某個使用 Microsoft.AspNet.WebApi.SelfHost 4.0.20918 NuGet Package 的 Console Application 專案使用 VS2017 開啟時出現 System.Net.Http 及 System.Net.Http.WebRequest 參照失效,改用 VS2015 開啟則無此問題。

VS2017 開啟失敗但 VS2015 正常的狀況之前遇過(VS2017 無法載入 MVC4 專案),但這回發生在 Console Appliation 專案,狀況不同。

優先檢查導致 NuGet 參照失敗的頭號戰犯 - .csproj 的 HintPath 設定 - 發現 System.Net.Http 的 HintPath 有正確指向 packages 目錄:

    <Reference Include="System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <HintPath>..\packages\Microsoft.Net.Http.2.0.20710.0\lib\net40\System.Net.Http.dll</HintPath>
    </Reference>

而 packages\Microsoft.Net.Http.2.0.20710.0\lib\net40\System.Net.Http.dll 確實存在,但我留意到有另一個目錄 net45,底下有個 _._ 空白檔案。

爬文學到新知識,_._ 檔案是用來確保 net45 資料夾在 ZIP 壓縮時不會被略過,而沒放 DLL 檔的 net45 資料夾代表 Package 相容於 .NET 4.5,但組件已內建於 GAC 不需額外複製安裝:

This is important because the existence of an "empty" net46 folder means that the package supports .NET Framework 4.6, but does not require any assemblies (DLLs) in order to run on that version of .NET. This is most likely because the implementation of the package is in the GAC.

專案為 .NET 4.5.2,故應改用 .NET 4.5+ 內建的 System.Net.Http.dll,換句話說,是參照 GAC 的 System.Net.Http 出了問題。回想專案升級 4.5.2 是很久以前的事,而升級後曾用 VS2017 編譯過,何以忽然不行?

鎖定關鍵字查到兩篇相關討論:

得到結論:這是 VS2017 15.5.x 的 Bug (我的 VS2017 版本是 15.5.7),將會在 VS2017 15.5.8 修正(目前進入 Preview 階段)。在修正釋出前,最簡單的 Workaround 是將 .csproj <Reference Include="System.Net.Http"> 及 <Reference Include="System.Net.Http.WebRequest"> 的 HintPath 刪除,即可藥到病除。

A web api self-host project failed to open in VS2017 but OK in VS2015, the error message is System.Net.Http reference not found. Finally I found it's a bug of VS2017 15.5.7 and the workaround is removing HintPath.


Comments

# by 棉花

文章最後一段"藥到命除".....這沒問題嗎XD

# by Jeffrey

to 棉花,哈哈哈哈,能錯成這樣自己都覺得好笑。謝謝指正。

# by not

推一下,今天也遇到這個問題,不過在 第一步 "優先檢查導致 NuGet 參照失敗的頭號戰犯 - .csproj 的 HintPath 設定 " 就解決了!

Post a comment