【发布时间】:2016-04-14 14:15:51
【问题描述】:
我使用的是System.Net.Http,我在网上找到了几个例子。我设法创建此代码以发出POST 请求:
public static string POST(string resource, string token)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "")
});
var result = client.PostAsync("", content).Result;
string resultContent = result.Content.ReadAsStringAsync().Result;
return resultContent;
}
}
一切正常。但是假设我想将第三个参数传递给POST 方法,一个名为data 的参数。数据参数是这样的对象:
object data = new
{
name = "Foo",
category = "article"
};
如果不创建KeyValuePair,我该怎么做?我的 php RestAPI 等待 json 输入,所以 FormUrlEncodedContent 应该正确发送 raw json。但是我怎么能用Microsoft.Net.Http 做到这一点?谢谢。
【问题讨论】:
-
如果我理解你的问题,你想发送 JSON 内容而不是正确的形式编码内容(并且通过扩展你希望你的匿名类型被序列化为 JSON 到该内容中)?
-
@CodingGorilla yes 是匿名类型。
-
作为对未来读者的附注,不要将
using用于HttpClient。 aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong -
来自 Microsoft 的说明为什么不应使用
using:HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors: Creating a new HttpClient instance per request. Server under heavy load. Creating a new HttpClient instance per request can exhaust the available sockets.docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/… -
旁注:
.Result将在任何具有同步上下文的环境中死锁。
标签: c# json dotnet-httpclient