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

Json相关问答推荐

Vega通孔信号中的动态梯度

褐煤面积图中的分选问题

简单条形图和有序分类中条形图的 colored颜色 梯度

如何避免解析 ISuperObject 类型字段中的 json 对象

删除 JOLT 中的方括号

如何使用 Google 表格应用程序脚本将 JSON 中的多个字段提取到 Google 表格中

如何使用 React 从 NASA IMAGES API 中解构所需信息

Vue 3如何将参数作为json发送到axios get

如何使用 jq 返回此 JSON 文件的文本字段?

当值包含ansible中的字符串时解析json值

Microsoft GRAPH 查询使用端点 /deviceManagement/deviceHealthScripts 列出了一种不熟悉的检测脚本内容格式

如何在golang中获取 struct 的json字段名称?

谷歌浏览器不允许我放置断点

在 JSON 对象中强制执行非空字段

Jsonpath 与 Jackson 或 Gson

如何使用 Newtonsoft.Json 包在 C#(4.0) 中解析我的 json 字符串?

如何使用 Serde 反序列化带有自定义函数的可选字段?

使用 Codable 序列化为 JSON 时的 Swift 字符串转义

Newtonsoft 对象 → 获取 JSON 字符串

如何在 postgresql 9.3 中循环 JSON 数组