我正在尝试使用HttpContent:
HttpContent myContent = HttpContent.Create(SOME_JSON);
...但是我没有找到它定义的DLL。
首先,我尝试添加对微软的引用。Http和系统。Net,但都不在列表中。我还尝试添加对System.Net.Http的引用,但HttpContent类不可用。
有人能告诉我在哪能找到HttpContent类吗?
我正在尝试使用HttpContent:
HttpContent myContent = HttpContent.Create(SOME_JSON);
...但是我没有找到它定义的DLL。
首先,我尝试添加对微软的引用。Http和系统。Net,但都不在列表中。我还尝试添加对System.Net.Http的引用,但HttpContent类不可用。
有人能告诉我在哪能找到HttpContent类吗?
当前回答
只使用……
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是抽象的,所以你需要使用一个派生类:
虽然最终版本的HttpContent和整个System.Net.Http命名空间将随.NET 4.5而来,但您可以通过从NuGet中添加Microsoft.Net.Http包来使用.NET 4版本
对于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/
就用微软。aspnet。webapi。client吧。
例子:
var client = HttpClientFactory.Create();
var result = await client.PostAsync<ExampleClass>("http://www.sample.com/write", new ExampleClass(), new JsonMediaTypeFormatter());
只使用……
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);