Microsoft.Net.Http vs Microsoft.AspNet.WebApi.Client

I need to access the REST service from a .NET application, and it looks like it can be done with either of these two packages. I don’t understand which package is supposed to be used in which scenarios. Can anyone bring more light into this?

+5
source share
1 answer

The short answer is yes, use Microsoft.AspNet.WebApi.Client .

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/

This package adds support for formatting and content negotiation for System.Net.Http. It includes support for JSON, XML, and URL encoded form data.

Microsoft.AspNet.WebApi.Client is actually dependent on Microsoft.Net.Http and extends HttpClient with some additional features that you will probably need to talk to with a RESTful service, such as ASP.NET web APIs (e.g. support JSON and XML).

Both packages work in the System.Net.Http namespace and revolve around the HttpClient class.

The Microsoft.AspNet.WebApi.Client package contains the System.Net.Http.Formatting.dll assembly, which adds some convenient extension methods to HttpClient and HttpContent (and others).

So for example:

 using (var client = new HttpClient()) { var response = await client.GetAsync("http://localhost/foo/api/products/1"); response.EnsureSuccessStatusCode(); var product = await response.Content.ReadAsAsync<ProductInfo>(); } 

The ReadAsAsync method is an extension method that Microsoft.AspNet.WebApi.Client adds to the HttpContent object. This automatically determines whether the response is JSON, XML, or the form is URL encoded (the above content matching) and then uses the appropriate formatter to de-serialize it into your strongly typed model (in this case, ProductInfo ).

If you try to use Microsoft.Net.Http, the ReadAsAsync method will not be available to you, and you can only read the content as raw data, such as bytes or strings, and they need to do serialization / de-serialization.

You also get extension methods for PUT / POST for a service in JSON or XML without having to do it yourself:

  // Save the ProductInfo model back to the API service await client.PutAsJsonAsync("http://localhost/foo/api/products/1", product); 

Key Microsoft.AspNet.WebApi.Client extensions:

https://msdn.microsoft.com/en-US/library/system.net.http.httpclientextensions.aspx https://msdn.microsoft.com/en-US/library/system.net.http.httpcontentextensions.aspx

+8
source

All Articles