HttpClient的和ReadAsAsync< T>()扩展方法方法、ReadAsAsync、HttpClient、GT

2023-09-04 08:21:20 作者:物是人非事事休

于是我开始了一个新的.NET 4.0的项目,并会做一个公共API一些工作。我计划使用微软的HttpClient类,所以我安装了Microsoft.Net.Http的NuGet软件包(2.2.13版)的最新稳定版本。我在看一些POC code,一个同事放在一起,也使用了HttpClient的一个的NuGet包,并注意到有code是这样的:

So I'm starting up a new .Net 4.0 project and will be doing some work with a public API. I'm planning on using the Microsoft HttpClient class so I installed the latest stable version of the Microsoft.Net.Http NuGet package (version 2.2.13). I'm looking at some POC code that a coworker put together, also using a NuGet package for HttpClient and notice that there's code like this:

HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAync("/uri").Result;

DomainType result = response.Content.ReadAsAsync<DomainType>().Result;

在我的项目,添加引用Microsoft.Net.Http包,当我尝试写类似code后,我注意到,Htt的presponseMessage没有一个 ReadAsAsync&LT; T&GT;()方法。做一些挖掘在我的同事的POC解决方案后,它看起来像 ReadAsAsync&LT; T&GT;()实际上是在 System.Net.Http扩展方法.Formatting 组装。在这个POC解决方案,有一个参考System.Net.Http.Formatting,但是它把该文件从路径 C:\ Program Files文件(x86)的\微软ASP.NET \ ASP.NET MVC 4 \大会\ System.Net.Http.Formatting.dll

In my project, after adding the reference to the Microsoft.Net.Http package, when I try to write similar code, I noticed that HttpResponseMessage doesn't have a ReadAsAsync<T>() method. After doing some digging in my coworker's POC solution, it looks like ReadAsAsync<T>() is actually an extension method in the System.Net.Http.Formatting assembly. In this POC solution, there's a reference to System.Net.Http.Formatting, however it's pulling this file from the path C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Net.Http.Formatting.dll.

我的问题是,有没有获得访问不是从我的本地ASP.Net安装引用此组装此扩展方法更好的解决办法?我担心的是,这会导致一个问题我们的CI服务器上,因为它不太可能安装ASP.Net。我想我可以复制System.Net.Http.Formatting到lib目录在我的解决办法,但我希望有一个更好的选择,如其他的NuGet包我丢失,会给我这个组件。

My question is, is there a better solution to getting access to this extension method than referencing this assembly from my local ASP.Net installation? My concern is that this is going to cause a problem on our CI server since it's not likely to have ASP.Net installed. I guess I could copy System.Net.Http.Formatting to a Lib directory in my solution but I'm hoping there's a better option such as another NuGet package I'm missing that would give me this assembly.

谢谢!

推荐答案

这就是的WebAPI客户端库包的一部分。安装Microsoft.AspNet.WebApi.Client的NuGet包。

That's part of the WebAPI client libraries package. Install the Microsoft.AspNet.WebApi.Client nuget package.