Can't find how to use HttpContent

2019-01-16 05:24发布

I am trying to use HttpContent:

HttpContent myContent = HttpContent.Create(SOME_JSON);

...but I am not having any luck finding the DLL where it is defined.

First, I tried adding references to Microsoft.Http as well as System.Net, but neither is in the list. I also tried adding a reference to System.Net.Http but the HttpContent class is not available.

So, can anyone tell me where I can find the HttpContent class?

7条回答
叼着烟拽天下
2楼-- · 2019-01-16 05:38

Just use...

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);
查看更多
相关推荐>>
3楼-- · 2019-01-16 05:38

To take 6footunder's comment and turn it into an answer, HttpContent is abstract so you need to use one of the derived classes:

enter image description here

查看更多
4楼-- · 2019-01-16 05:41

I'm pretty sure the code is not using the System.Net.Http.HttpContent class, but instead Microsoft.Http.HttpContent. Microsoft.Http was the WCF REST Starter Kit, which never made it out preview before being placed in the .NET Framework. You can still find it here: http://aspnet.codeplex.com/releases/view/24644

I would not recommend basing new code on it.

查看更多
beautiful°
5楼-- · 2019-01-16 05:48

The class is listed as being present in the System.Net.Http assembly. Note that this class is new for .NET 4.5, so you need to be using that version of the BCL.

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-16 05:48

For 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/

查看更多
放荡不羁爱自由
7楼-- · 2019-01-16 05:51

The System.Net.Http namespace (where HttpContent class resides) is new to .Net 4.5, are you using a VS2012 RC?

Otherwise, you wouldn't have access to this.

查看更多
登录 后发表回答