Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to access REST service from .NET application and it seems it can be done with any of those two packages. It's not clear to me which package is supposed to be used in which scenarios. Can anyone bring more light into this?

like image 387
Anil Avatar asked Jul 07 '15 07:07

Anil


People also ask

What is Microsoft AspNet WebApi core?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the . NET Framework. 133.0M. Microsoft.AspNet.WebApi.Owin.


1 Answers

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 to System.Net.Http. It includes support for JSON, XML, and form URL encoded data.

Microsoft.AspNet.WebApi.Client actually depends on Microsoft.Net.Http, and extends the HttpClient with some more features that you would likely need to talk to a RESTful service such as ASP.NET Web API (e.g. JSON and XML support).

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

The Microsoft.AspNet.WebApi.Client package contains the System.Net.Http.Formatting.dll assembly, which adds some handy 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 onto the HttpContent object. This automatically figures out if the response is JSON, XML or form URL encoded (the aforementioned content negotiation), and then uses the corresponding formatter to de-serialize it into your strongly typed model (in this case, ProductInfo).

If you tried to just use Microsoft.Net.Http, the ReadAsAsync method wouldn't be available to you, and you'd only be able to read the content as raw data such as bytes or string, and have to do the serializing / de-serializing yourself.

You also get extension methods to PUT / POST back to the service in JSON or XML without having to do that 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

like image 190
David Moore Avatar answered Sep 17 '22 16:09

David Moore