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?
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?
简短的答案是肯定的,使用Microsoft.AspNet.WebApi.Client
.
https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/个
该软件包增加了对格式设置和内容协商的支持
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).
这两个包都在System.Net.Http
名称空间中运行,并围绕键HttpClient
类运行.
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>();
}
ReadAsAsync
方法是Microsoft.AspNet.WebApi.Client
添加到HttpContent
对象上的扩展方法.这会自动确定响应是JSON、XML还是表单URL编码的(前面提到的内容协商),然后使用相应的格式化程序将其反序列化到强类型模型中(在本例中为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