找不到 System.Net.Http 4.2.0.0 的奇怪问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47570912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 09:58:53  来源:igfitidea点击:

Strange issue with System.Net.Http 4.2.0.0 not found

.netvisual-studio-2017dotnet-httpclientservice-fabric-stateless

提问by OliverB

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.

我有一个简单的类库项目(完整的 .NET 框架,4.6.1),其中包含一个用于 Cosmos DB 功能的包装类。因此,我在此项目中添加了“Microsoft.Azure.DocumentDB”NuGet 包 1.19.1。除此之外,我参考了“Newtonsoft.Json”NuGet Package 10.0.3,以及几个“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:

但是一旦我点击了我的包装类——从一个简单的 Service Fabric 无状态服务(完整的 .NET Framework 4.6.1)消费——并尝试执行以下代码行:

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

System.IO.FileNotFoundException 发生 HResult=0x80070002
消息=无法加载文件或程序集“System.Net.Http,版本=4.2.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a”或其依赖项之一。该系统找不到指定的文件。
源 = StackTrace:在 Microsoft.Azure.Documents.Client.DocumentClient.Initialize(Uri 1 desiredConsistencyLevel) at Microsoft.Azure.Documents.Client.DocumentClient..ctor(Uri serviceEndpoint, String authKeyOrResourceToken, ConnectionPolicy connectionPolicy, NullableserviceEndpoint , ConnectionPolicy connectionPolicy, Nullable 1 desiredConsistencyLevel)

内部异常 1:FileNotFoundException:无法加载文件或程序集“System.Net.Http,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a”或其依赖项之一。该系统找不到指定的文件。

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

我完全不知道为什么根本找不到 System.Net.Http 程序集 - 在我的类库项目中甚至有一个对 .Net Framework 程序集“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):

我也不明白的是,有一个奇怪的绑定重定向到 4.2.0.0——那个来自哪里?为了解决这个问题,我尝试将以下重定向添加到 Service Fabric 服务(使用类库)的 app.config:

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

但仍然没有区别,我仍然在运行时收到错误。

Anybody having a clue? Anybody having seen such issue?

有人有线索吗?有人见过这样的问题吗?

Thanks and regards, OliverB

感谢和问候, OliverB

回答by Andrei U

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.Httpwhich is 4.3.3 contains the dll version 4.1.1.2.

您面临的问题与 Visual Studio 相关,尤其是System.Net.Http v4.2.0.0. 但是,采用新的方式,任何引用都应该通过 NuGet 完成,最新版本System.Net.Http是 4.3.3 包含 dll 版本 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.

问题是 VS 在构建时和运行时也会忽略您的引用,它会尝试引用它知道的 DLL。

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

  • 确保对 System.Net.Http 的任何引用都是通过 NuGet 完成的
  • 构建时错误:更改随 VS 2017 ( c:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\)一起提供的 System.Net.Http.dll 的扩展名(或将其移动到其他地方...基本上摆脱它);如果您有不同的版本,则路径会略有不同,但差别不大
  • 运行时错误:添加程序集绑定重定向

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.

如果您在 google 上在线查看,您会发现 Microsoft 有一些关于此的未解决问题,因此希望他们将来会解决此问题。

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

在寻找针对此问题的一些永久性修复程序以在构建代理上工作时,注意到如果您迁移到新的 NuGet PackageReference 模型(.csproj不在 中packages.config)往往会更好地工作。这是有关如何进行此升级的指南的链接:https: //docs.microsoft.com/en-us/nuget/reference/migrate-packages-config-to-package-reference

回答by 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" />

回答by Ogglas

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

除了@AndreiU 已经给出的答案以及如何在本地重现运行时错误。

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

部署到 Azure 而不是本地时,我收到以下运行时错误。

{"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)"}}

无法加载文件或程序集“System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或其依赖项之一。系统找不到指定的文件。","ExceptionType":"System.IO.FileNotFoundException","StackTrace":" at Company.Project.Service.CompanyIntegrationApiService..ctor(Uri baseAddress)\r\n at Company.Project .BackOffice.Web.Controllers.OrderController..ctor() 在 C:\projects\company-project\src\Company.Project.BackOffice.Web\Controllers\Order\OrderController.cs:line 30\r\n 在 lambda_method(关闭 )\r\n 在 System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}} Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' 或其依赖项之一。系统找不到指定的文件。","ExceptionType":"System.IO.FileNotFoundException","StackTrace":" at Company.Project.Service.CompanyIntegrationApiService..ctor(Uri baseAddress)\r\n at Company.Project .BackOffice.Web.Controllers.OrderController..ctor() 在 C:\projects\company-project\src\Company.Project.BackOffice.Web\Controllers\Order\OrderController.cs:line 30\r\n 在 lambda_method(关闭 )\r\n 在 System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}} Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' 或其依赖项之一。系统找不到指定的文件。","ExceptionType":"System.IO.FileNotFoundException","StackTrace":" at Company.Project.Service.CompanyIntegrationApiService..ctor(Uri baseAddress)\r\n at Company.Project .BackOffice.Web.Controllers.OrderController..ctor() 在 C:\projects\company-project\src\Company.Project.BackOffice.Web\Controllers\Order\OrderController.cs:line 30\r\n 在 lambda_method(关闭 )\r\n 在 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 项目和服务项目针对System.Net.Http.

Web project:

网络项目:

enter image description here

在此处输入图片说明

Service project:

服务项目:

enter image description here

在此处输入图片说明

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

很容易认为这是由版本不匹配引起的,但这里的关键是查看错误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.

查看 path 属性,我们可以看到 Web 项目的目标是 .Net Framework 程序集,而服务的目标是 Visual Studio 2017 的程序集。由于服务器没有安装 Visual Studio 2017,因此会发生运行时错误。

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 Studio17\Professional\MSBuild\Microsoft\Microsoft.NET.Build.Extensions\net461\lib\System.Net.Http.dll

Something as simple as setting Copy Localto truecan fix the problem, however not in all cases.

一些简单的设置Copy Localtrue可以解决问题,但不是在所有情况下。

enter image description here

在此处输入图片说明

In order to reproduce the error on your local machine, simply remove the needed System.Net.Http.dllfrom 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.

为了在本地机器上重现错误,只需System.Net.Http.dll从 Visual Studio 特定文件夹中删除所需的。这会给你运行时错误和可能的一些构建错误。修复这些之后,一切都应该可以工作了,至少对我来说是这样。

If you have installed System.Net.Httpvia NuGetcheck which assembly is used by looking at the .csprojversion. System.Net.Http 4.3.4gives the following assembly for example:

如果您已System.Net.Http通过NuGet查看.csproj版本检查使用哪个程序集进行安装。System.Net.Http 4.3.4例如给出以下程序集:

<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>
  <Private>True</Private>
</Reference>

If you use a build server like Jenkins, TeamCity or AppVeyor the runtime missing .dllmight exist there as well. In this case it might not help to use NuGet version of System.Net.Http or deleting the missing .dlllocally. 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.configor App.configdepending on your project. In my case I would like to use 4.0.0.0 instead:

如果您使用像 Jenkins、TeamCity 或 AppVeyor 这样的构建服务器,运行时缺失.dll也可能存在。在这种情况下,使用 System.Net.Http 的 NuGet 版本或在.dll本地删除丢失的内容可能无济于事。要解决此错误,请查看未找到的版本和特定的PublicKeyToken. 之后,在您的项目中Web.configApp.config根据您的项目创建绑定重定向。就我而言,我想改用 4.0.0.0:

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

关于这个问题的一个很好的 Github 线程:

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

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

回答by Leniel Maccaferri

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

我刚刚System.Net.Http使用 NuGet安装。你可以在这里抓住它:

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

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

The ASP.NET MVCproject I'm working on targets .NET 4.6.1. It works perfectly on my machine while debugging in IIS Expresswith Visual Studio 2019.

ASP.NET MVC我正在研究的项目目标.NET 4.6.1。它在我的机器上完美运行,同时IIS Express使用 Visual Studio 2019进行调试。

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

尝试运行部署到 Azure 的应用程序时出现问题。我收到此错误:

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

无法加载文件或程序集“System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a”或其依赖项之一。

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

在我的情况下真正有效的是打开 .csproj 文件并在System.Net.Http以下屏幕截图中搜索类似的内容...

enter image description here

在此处输入图片说明

See that the .csprojfile has the version 4.1.1.3:

查看该.csproj文件的版本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 ..\packagesfolder 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.

<HintPath>实际指向..\packages从的NuGet,也就是文件夹,这是由安装的NuGet真实版。一旦部署,这个特定版本也将在服务器端恢复,一切都应该与绑定重定向一起工作。

... and so the binding redirectshould mention this specific version in Web.configlike this:

...所以绑定重定向应该Web.config像这样提到这个特定版本:

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

在向Azure Kudu提交几次后,这解决了我的问题。Azure 网站最终启动时没有出现错误。

回答by Jamie R Rytlewski

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

我为解决这个问题所做的是从 web.config 中删除了所有绑定并做了一个

Update-Package -reinstall

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.

这删除了一堆可能不需要在那里的旧绑定,并且实际上做了很好的清洁。

回答by Mark

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.

当我将 Web 服务部署到我们的一台服务器时遇到此错误。该项目针对 .Net 框架 4.7.2,该框架未安装在服务器上。在服务器上安装 4.7.2 框架更正了问题。

回答by 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:

Andrei U 的回答导致了我的救赎。但是,推理与我的情况不符。对于和我一样情况的人:

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.

这是一个运行时错误(不是构建时间),构建成功,但可以在一台计算机上运行,​​但不能在服务器上运行。解决方案: - 添加了 System.Net.Http 包。- 重命名文件:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.2\System.Net.Http.dll(例如重命名为:System.Net.Http.dll.BAK)构建服务器。

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

我没有并且仍然没有这个 dll 的程序集重定向

回答by 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

在为此苦苦挣扎了几天之后,我终于为我的项目解决了 .Net 4.7.2/System.Net.Http 问题。除了更改 *.csproj 文件以针对框架版本 4.7.2 我还必须更新项目中的 app.config

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

to:

到:

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

回答by Raquib

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

我发现一个简单的解决方案是将 Web 项目的目标框架降级到 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.

我创建客户端和 Web 应用程序,客户端具有 .net framework 4.7.1 和 web 具有相同的,我面临同样的问题,当我降级目标 .net framework for web 时,它对我有用。

回答by Rajmond Burgaj

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.

对我来说真的很奇怪。发现问题后需要进行数小时的调试。它没有发生在本地,而是仅在使用 jenkins 构建项目时发生。

I had a small library using dotnet standart 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 dotnet standart library I had some code that looked like this:

我有一个使用 dotnet 标准 2.0 的小型库,主要项目是基于普通 .NET 的 WCF 项目(我的特别是 v4.6.1)。但是在 dotnet 标准库的启动类中,我有一些看起来像这样的代码:

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:

IStaticDataConfiguration 界面如下所示:

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

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

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

此接口位于 dotnet 标准库内部,而实现则位于外部(位于 WCF 项目中)。

From outside of the library I was calling the AddStaticDataConfigurationmethod like below:

从库外,我正在调用如下AddStaticDataConfiguration方法:

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 dotnet standart library which for some crazy reason dotnet standart does not like and maybe it thinks HttpClientis coming from different classes, as a result throwing System.Net.Http 4.x.x.xnot found exception. When removed the code to not accept a HttpClientfrom a normal .NET project but creating a new funcinside the library itself its happy and working fine. Hope this might help somebody else since this error is happening for so many reasons :)

问题是我将一个Func<HttpClient>普通的 .NET 项目传递给一个 dotnet 标准库,出于某种疯狂的原因,dotnet 标准库不喜欢它,也许它认为HttpClient来自不同的类,结果抛出了System.Net.Http 4.x.x.x未找到的异常。当删除代码以不接受HttpClient来自普通 .NET 项目但func在库本身内部创建一个新的代码时,它很高兴并且工作正常。希望这可能对其他人有所帮助,因为发生此错误的原因有很多:)