Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't find how to use HttpContent

Tags:

c#

.net

asp.net

dll

People also ask

What is HttpContent?

A base class representing an HTTP entity body and content headers.

What is Post async?

PostAsync(String, HttpContent) Send a POST request to the specified Uri as an asynchronous operation. PostAsync(Uri, HttpContent) Send a POST request to the specified Uri as an asynchronous operation.

What is Formurlencodedcontent C#?

A container for name/value tuples encoded using application/x-www-form-urlencoded MIME type.


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);

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


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/


While the final version of HttpContent and the entire System.Net.Http namespace will come with .NET 4.5, you can use a .NET 4 version by adding the Microsoft.Net.Http package from NuGet