我正在尝试使用HttpContent:

HttpContent myContent = HttpContent.Create(SOME_JSON);

...但是我没有找到它定义的DLL。

首先,我尝试添加对微软的引用。Http和系统。Net,但都不在列表中。我还尝试添加对System.Net.Http的引用,但HttpContent类不可用。

有人能告诉我在哪能找到HttpContent类吗?


当前回答

对于JSON Post:

var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Non-JSON:

var stringContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("field1", "value1"),
    new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/

其他回答

只使用……

var stringContent = new StringContent(jObject.ToString());
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Or,

var stringContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

要获取6footunder的注释并将其转换为答案,HttpContent是抽象的,所以你需要使用一个派生类:

就用微软。aspnet。webapi。client吧。

例子:

var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());

对于JSON Post:

var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

Non-JSON:

var stringContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("field1", "value1"),
    new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);

https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/

我非常确定代码没有使用System.Net.Http.HttpContent类,而是使用Microsoft.Http.HttpContent。 微软。Http是WCF REST入门套件,它在被放入。net框架之前从未发布过预览版。 你仍然可以在这里找到它:http://aspnet.codeplex.com/releases/view/24644

我不建议在此基础上编写新代码。