After spending many days on various projects, trying to fix this recurrent hell: here is a reliable fix that does not break after some time. Tested with 4.6.1 and 4.7.2.
Fix process
Fix your developer machine:
- Remove all references to the nuget package "
System.Net.Http
"
- Open the "
%ProgramFiles(x86)%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2
" directory (adapt to your specific version).
- In this directory: locate the special file
System.Net.Http.dll
- In this directory: rename "
System.Net.Http.dll
" to "System.Net.Http.dll.backup
"
Do that on all developer machines. This will not break your machine.
In your projects: just add basic "Assembly Reference" for "System.Net.Http".
In your runnable projects (Web/CLI): you might need to set the project reference as "Copy local" to have the correct dll copied when publishing somewhere else.
<Reference Include="System.Net.Http">
<Private>true</Private>
</Reference>
You may add this assembly redirect (app.config/web.config) in some cases:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
Why does this work?
It seems the build process is able to see this special file exists. The build will then generate problematic references. This will lead to the exceptions you know well.
Making the file invisible (due to the file extension change) will prevent the build process from doing this crazy stuff.
What is this specific file? Is it special?
This file is fake news. Decompile it, you will see it is empty!
They just put it there to turn us crazy [citation needed].
Locations may vary:
- when SDK installed:
- "
%ProgramFiles(x86)%\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2
"
- without SDK:
- "
%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib
"
Wait, you can't delete a system file!
That's what I (and others) concluded for some years. This problem continues to come back many times a year. This solution is not as bad as you think, since the problematic file is a FAKE assembly.
Learn more
This dotnet issue on github contains a huge volume of information about the problem. This answer explains the transitive dependency phenomenon that is part of the global problem. This answer suggests deleting the bad dlls.
Oops, it seems I am partially duplicating Steven Elliott's answer. Mine is more detailed though.