ChatGPT解决这个技术问题 Extra ChatGPT

Strange issue with System.Net.Http 4.2.0.0 not found

I have a strange issue, which drives me crazy…

I have a simple Class Library Project (Full .NET Framework, 4.6.1) with a wrapper class for functionality around Cosmos DB. Therefore I have added the “Microsoft.Azure.DocumentDB” NuGet Package 1.19.1 to this project. Other than that, I have a reference to the “Newtonsoft.Json” NuGet Package 10.0.3, as well as to a couple of "Microsoft.Diagnostics.EventFlow.*" NuGet Packages.

So far, everything compiles without any error.

But as soon as I hit my wrapper class – consumed from a simple Service Fabric Stateless Service (Full .NET Framework 4.6.1) – and try to execute the following line of code:

_docClient = new DocumentClient(new Uri(cosmosDbEndpointUrl), cosmosDbAuthKey);

I get this strange error at runtime:

System.IO.FileNotFoundException occurred HResult=0x80070002 Message=Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified. Source= StackTrace: at Microsoft.Azure.Documents.Client.DocumentClient.Initialize(Uri serviceEndpoint, ConnectionPolicy connectionPolicy, Nullable1 desiredConsistencyLevel) at Microsoft.Azure.Documents.Client.DocumentClient..ctor(Uri serviceEndpoint, String authKeyOrResourceToken, ConnectionPolicy connectionPolicy, Nullable1 desiredConsistencyLevel) Inner Exception 1: FileNotFoundException: Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I have absolutely no clue, why the System.Net.Http assembly is not found at all – there is even a assembly reference in my class library project to the .Net Framework Assembly “System.Net.Http 4.0.0.0”.

What I also do not understand is, that there is this weird binding redirect to 4.2.0.0 – where is that one coming from? To get around this one, I tried to add the following redirect to the app.config of the Service Fabric Service (which is consuming the class library):

But still no difference, I still get the error at runtime.

Anybody having a clue? Anybody having seen such issue?

Hi, OliverB! Did you find a workaround for this issue? I'm just facing the same situation and it's a nightmare :-(
If top 5 answers don't work for you, see my answer below about adding assemblies to compilation section of web.config.

G
Ganesh Jadhav

The problem you're facing is related to Visual Studio, especially 2017 which is shipped with System.Net.Http v4.2.0.0. However, adopting the new way whereby any references should be done via NuGet, latest version of System.Net.Http which is 4.3.3 contains the dll version 4.1.1.2.

The problem is that VS at build time and at run time as well will ignore your reference and it will try to reference the DLL it knows about.

How to fix it:

make sure that any references to System.Net.Http are done via NuGet

Build time errors: change extension of System.Net.Http.dll (or move it somewhere else...basically get rid of it) that is shipped with VS 2017 (c:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\); if you've got a different version then the path will slightly differ, not much though

Runtime errors: add an assembly binding redirect

If you look online on google you'll find a few open issues with Microsoft about this, so hopefully they'll fix this in the future.

Hope this helps.

Update:

When looking at finding some permanent fixes for this issue to work on the build agents, noticed that if you migrate to the new NuGet PackageReference model (in .csproj not in packages.config) tends to work better. Here's a link to the guide on how to do this upgrade: https://docs.microsoft.com/en-us/nuget/reference/migrate-packages-config-to-package-reference


Seems like they're bumping the vesion in net472 github.com/Microsoft/dotnet-framework-early-access/blob/master/…
Many thanks, been going mad trying to solve this for the last few hours!
Just a heads up that the issue might be solved by actually removing the bindingRedirects if you're working with .NET 4.7.2.
Same problem today when upgrading to 4.7.2. System.IO.Compression and System.Runtime were also affected. Removing the binding redirects solved the problem.
Yes! Finally! As per @Alternatex and JB above, for 4.7.2 remove the bindingRedirects and now golden. What a pain for every framework update figuring out the latest song and dance routine needed for System.Net.Http.
V
Vivek Sharma

Removing binding redirect worked for me, you can try removing it:

<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />

That was one of the 1st things I tried, but without success
Removing the bindingRedirect solved the problem for me. The unit tests were not passing with the same error as OP and now they work.
Is this the full codeline? And where exactly does this need to be added? All my other bindingRedirects are at wrapped in tag dependentAssembly
This worked great. I would add, if you have multiple projects in your solution, make sure you evaluate all of them and resolve using this method.
Thank you. Been stuck on the issue from 2 days on this. It worked !!!
a
abatishchev

An addition to the answer @AndreiU already gave and how to reproduce runtime errors locally.

I got the runtime error below when deploying to Azure, not locally.

{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'OrderController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.","ExceptionType":"System.IO.FileNotFoundException","StackTrace":" at Company.Project.Service.CompanyIntegrationApiService..ctor(Uri baseAddress)\r\n at Company.Project.BackOffice.Web.Controllers.OrderController..ctor() in C:\projects\company-project\src\Company.Project.BackOffice.Web\Controllers\Order\OrderController.cs:line 30\r\n at lambda_method(Closure )\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}

When I started looking at assemblies I could see that my web project and service project targeted different versions for System.Net.Http.

Web project:

https://i.stack.imgur.com/Zid7c.png

Service project:

https://i.stack.imgur.com/eS0SH.png

It's easy to think that this is caused by a mismatch in versions but the key here is to look at the error The system cannot find the file specified..

Looking at the path property we can see that the web project targets a .Net Framework assembly while the service targets an assembly from Visual Studio 2017. Since the server does not have Visual Studio 2017 installed, the runtime error will occur.

Web path:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Net.Http.dll

Service path:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.Net.Http.dll

Something as simple as setting Copy Local to true can fix the problem, however not in all cases.

https://i.stack.imgur.com/vnX5w.png

In order to reproduce the error on your local machine, simply remove the needed System.Net.Http.dll from the Visual Studio specific folder. This will will give you the runtime error and probably some build errors. After these are fixed everything should work, at least it did for me.

If you have installed System.Net.Http via NuGet check which assembly is used by looking at the .csproj version. System.Net.Http 4.3.4 gives the following assembly for example:

<Reference Include="System.Net.Http, Version=4.1.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
  <HintPath>..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll</HintPath>
  <Private>True</Private>
</Reference>

If you use a build server like Jenkins, TeamCity or AppVeyor the runtime missing .dll might exist there as well. In this case it might not help to use NuGet version of System.Net.Http or deleting the missing .dll locally. To solve this error look at the version that is not found and the specific PublicKeyToken. After that create a binding redirect in either Web.config or App.config depending on your project. In my case I would like to use 4.0.0.0 instead:

<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>

A good Github thread about the issue:

https://github.com/dotnet/corefx/issues/22781


adding
For me as well! Thank you for a workaround! oldVersion="0.0.0.0-4.2.0.0" newVersion="4.1.1.3" since I'm using 4.1.1.3
The redirect to 4.0.0.0 is what put me over the top. Thanks!
It is dangerous to redirect down! You have a dependency in your project signaling it uses 4.2 but you force it to use 4.0. If it is using any of the new properties or method introduced post 4.0 you will get a runtime failure at difficult to predict time.
The link to the github thread is dead. But the following thread seems to contain the relevant discussion: github.com/dotnet/runtime/issues/24382
L
Leniel Maccaferri

I just installed System.Net.Http using NuGet. You can grab it here:

https://www.nuget.org/packages/System.Net.Http/

The ASP.NET MVC project I'm working on targets .NET 4.6.1. It works perfectly on my machine while debugging in IIS Express with Visual Studio 2019.

The problem happened when trying to run the application deployed to Azure. I was getting this error:

Could not load file or assembly 'System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

What really worked in my case was opening the .csproj file and searching for System.Net.Http like in the following screenshot...

https://i.stack.imgur.com/JObUK.jpg

See that the .csproj file has the version 4.1.1.3:

<Reference Include="System.Net.Http, Version=4.1.1.3, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">

The <HintPath> actually points to the ..\packages folder from Nuget, that is, this is the real version installed by Nuget. Once deployed this specific version will also be restored on the server side and everything should work with a bind redirect.

... and so the binding redirect should mention this specific version in Web.config like this:

<dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.1.1.3" />
</dependentAssembly>

This fixed the problem in my case after a couple of commits to Azure Kudu. The Azure web site finally started with no errors.


J
Jamie R Rytlewski

What I did to fix the issue was removed all the bindings from the web.config and did a

Update-Package -reinstall

This removed a bunch of the old bindings that probably do not need to be there and actually did a good cleaning.


M
Mark Willis

I encountered this error when I deployed a web service to one of our servers. The project targeted .Net framework 4.7.2, which wasn't installed on the server. Installing the 4.7.2 framework on the server corrected the problem.


This was my issue too. It is a reoccurring topic for other versions as well.
S
Sam

The answer of Andrei U lead to my salvation. However, the reasoning didn't match with my case. For people who are in the same scenario as me:

It was a runtime error (not build time), where the build succeeded, but would work on one computer, but not the server. Solution: - Added System.Net.Http package. - Rename file: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.2\System.Net.Http.dll (eg rename to: System.Net.Http.dll.BAK) on the build server.

I didn't have and still don't have assembly redirects for this dll


P
P.Brian.Mackey

I believe part of the answer can be found in Microsoft's documentation.

When you create a desktop app in Visual Studio that targets the .NET Framework 4.5.1 or a later version, the app uses automatic binding redirection.

As @Vivek Sharma's answer points out, removing:

<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />

resolved the problem in 3 such cases in my app. When you examine the DLL with Powershell, for example:

 ([system.reflection.assembly]::loadfile("C:\MyApp\bin\System.Net.Sockets.dll")).FullName

Outputs

System.Net.Sockets, Version=4.0.0.0

Clearly a binding redirect to 4.2.0.0 isn't going to work because we are outputting 4.0.0.0 to the bin.

It's also worth checking the GAC to see if the assembly is also missing from there:

 gacutil -l System.Net.Sockets

In my case the particular version was also missing from the GAC. If the DLL were in the GAC then it should have been found in the assembly binding process.


C
CrnaStena

Along with many suggestions above, this is what worked for me:

Remove Nuget package 4.3.4 (I had to downgrade another package that required it) Add System.Net.Http as Reference (version 4.2.0.0) Remove bindingRedirect Add System.Net.Http to the compilation section in Web.config(s).

If you have Areas, add it to their Web.config as well. At least I had to in my code.


This solved my problem about it worked on local VS but not in Azure DevOps.
R
Raquib

One simple solution I found that downgrade the target framework for web project to 4.6.

I create client and web application, client having .net framework 4.7.1 and web having the same and I am facing same issue, when I downgrade target .net framework for web it's work for me.


B
Bruno

My solution was similar to @Raquib's. My project was 4.7.2 and worked just fine on my PC. Whenever I deployed to our dev server I would get the issue mentioned in the question. Turns out the highest .net version on the server was 4.6.1. Downgrading my project to 4.6.1 fixed the problem. Upgrading the server's .net version was not an option for me.


U
Umar Topia

I tried out various solutions (removing the dependentAssembly OR specifying the binding redirect as well). None of them worked.

However, the only solution which worked for me was to explicitly set Specific Version for System.Net.Http (or whatever DLL giving you version issues) to False from Visual Studio.

https://i.stack.imgur.com/UW8qs.png


This worked for me for a project which was multi-targeting different frameworks i.e. net472, net72 etc
H
Harish Ninge Gowda

I faced a similar issue and with lot of difficulties resolved it. I am using Visual Studio 2019

Remove any assembly references to System.Net.*(any package that starts with System.Net) Uninstall all the packages that start with System.Net.* Install Microsoft.AspNet.WebApi.Client from package manager The above should fix your issue. In any case you still have the issue. Intellisense will suggest you to add reference to System.Net.Http, click on add reference. In my case it suggested for two references System.Net.Http and System.Net.Http.Formatting. After clicking add it worked fine.


B
Ben Bradley

I had a similar problem. Trying to remove the System.Net.Http NuGet package (which is version 4.1.1.2) fails as it's marked as a prerequisite to other packages I was using.

I tried removing all binding redirects as mentioned in several of the answers here. While that didn't work on it's own, I continued with the following.

In the References node under all my projects I removed the link to the System.Net.Http.dll from the NuGet package and added the one from C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.6.1\System.Net.Http.dll

With all these references changed and no binding redirect the projects built and ran.


u
user8862383

I had the same problem. In the end I solved it by changing the Deploy-FabricApplication.ps1 to something like this

$binFolder = "$LocalFolder\..\..\..\..\Bin"

$httpDllLocation = "$binFolder\System.Net.Http.dll"
$codeFolder = "$ApplicationPackagePath\[ProjectName].ServicesPkg\Code"
$configFile = "$codeFolder\[ProjectName].Services.exe.config"

Copy-Item $httpDllLocation -Destination $codeFolder 

$appConfig = [xml](cat $configFile)
$appConfig.configuration.runtime.assemblyBinding.dependentAssembly | foreach {

    $name = $_.assemblyIdentity.name
    #Write $name
    if($name -eq 'System.Net.Http')
    {
        Write 'System.Net.Http changed'

        $_.bindingRedirect.newVersion = '4.2.0.0'
    }
}
$appConfig.Save($configFile)

I found an 4.2.0.0 System.Net.Http.dll that is x64. Before deploying this script copies the dll to the package directory and changes the config file to explicitly use this file. I also wrote a blog about my System.Net.Http problems at http://gertjanvanmontfoort.blogspot.nl/2017/11/systemnethttp-dll-version-problems.html

Do not forget to replace the [ProjectName] with your own project name

Hope this helps, feel free to ask


D
Doug Boone

After struggling with this for a couple of days I finally got the .Net 4.7.2/System.Net.Http problem fixed for my project. In addition to changing the *.csproj file to target the framework version 4.7.2 I had to also update app.config in the projects from

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />

to:

<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />

v
vr_driver

Overnight our application stopped uploading data to our third party provider. I'm presently using VS 2017 15.9.27 and my error "The process failed: The underlying connection was closed: An unexpected error occurred on a send." was from this line:

Dim stream As IO.Stream = request.GetRequestStream

With the request originating from this:

Dim request As Net.HttpWebRequest = Net.HttpWebRequest.Create(uri)

I did two things to resolve the problem. I upgraded to the most recent version of .NET to 4.6.1, which now produced the following error:

"Could not load file or assembly 'System.Net.Http, Version=4.2.0.0," 

To solve the newly created problem, I removed the package "System.Net.Http" and instead added it back by NuGet to 4.3.4.

I suspect that it could have been a certificate or protocol problem, as it installed the following Security references which weren't there before:

System.Security.Cryptography.Algorithms (>= 4.3.0)
System.Security.Cryptography.Encoding (>= 4.3.0) 
System.Security.Cryptography.Primitives (>= 4.3.0)
System.Security.Cryptography.X509Certificates (>= 4.3.0)

m
mycroes

For me was something really strange. Needed hours of debugging after found what was the issue. It did not happen locally but only when using Jenkins to build the project.

I had a small library using netstandard 2.0 and the main project was WCF project which is based on normal .NET(mine was specifically v4.6.1). But in the startup class of the netstandard library I had some code that looked like this:

public static class CoreModule
{
    public static IServiceCollection AddStaticDataConfiguration(
        this IServiceCollection services, Func<IServiceProvider, IStaticDataConfiguration>  staticDataConfiguration) 
    {  
        services.TryAddSingleton(staticDataConfiguration);
        services.TryAddSingleton<Func<HttpClient>>(x =>
        {
            var configuration = staticDataConfiguration(x);

            return configuration.ClientResolver ?? (() => new HttpClient());
        });
        return services;
    }
}

IStaticDataConfiguration interface looks like below:

public interface IStaticDataConfiguration
{
    //..... some stuff

    Func<HttpClient> ClientResolver { get; set; }
}  

This interface resides inside of the netstandard library while the implementation is outside of it(its located in WCF project).

From outside of the library I was calling the AddStaticDataConfiguration method like below:

serviceCollection.AddStaticDataConfiguration(p =>
{
    var staticDataConfig = p.GetService<IStaticDataConfiguration>();
    return new StaticDataProviderConfiguration
    {
        //...some other stuff
        ClientResolver = () => restRequestFactory.GetInstrumentedClient("StaticDataService") //this returns an HttpClient
    };
});

The problem is that I am passing a Func<HttpClient> from a normal .NET project to a netstandard library which for some crazy reason netstandard does not like and maybe it thinks HttpClient is coming from different classes, as a result throwing System.Net.Http 4.x.x.x not found exception. When removed the code to not accept a HttpClient from a normal .NET project but creating a new func inside the library itself its happy and working fine. Hope this might help somebody else since this error is happening for so many reasons :)


J
Jadran Grba

I was using .net 4. And my 'System.Net.Http' reference was pointing to '.net 4.7' version of dll. So I changed the .dll path to pointing to 'Microsoft.Net.Http' package and rebuild it. This resolved my problem.

https://i.stack.imgur.com/PaeqD.png


f
fiffens

Had the solution compiling and running fine on multiple dev machines except one which gave this error when running the project. Deleting all files and retrieving them from TFS did not help.

A Visual Studio Repair solved it.

From Visual Studio Installer do a Repair.

Visual Studio 2019 Version 16.11.5


a
alamoot

In my case, I removed all dependencies and their binding redirects under the <runtime> tag from the .config file. I built the solution that gave me binding errors. Clicking on the error, VS populated only the dependencies and their redirects as needed, and was able to run the solution after.


B
Bogdan M.

What worked for me was to downgrade System.Net.Http to version 4.0 so that all the packages and dependencies will use the same version:

  <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>

and I deleted the System.Net.Http.dll from all the subfolders of C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Microsoft\Microsoft.NET.Build.Extensions and C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework.


S
Shadab Shamim

As a workaround I installed System.Buffer 4.5.0 version which has a dependency on System.Net.Http dll version 4.2.0.0. Hence After installing you will see the System.Net.Http dll with above version in the bin folder of the project. Which is an easy workaround for such issues.


O
Obsidian

First delete from your local filesystem:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\Syste.Net.Http.dll

Then remove all references in Projects and, add 4.0 reference. This solved my problem to me.


oh my no, please do not corrupt your installation of VS by deleting some of its files.
What a great idea. I wonder how I didn't come up with this one. :)