HttpClient and ReadAsAsync() extension method

2019-04-04 08:56发布

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;

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.

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.

Thanks!

1条回答
我命由我不由天
2楼-- · 2019-04-04 09:20

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

查看更多
登录 后发表回答