c# – Cant find how to use HttpContent

c# – Cant find how to use HttpContent

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 6footunders comment and turn it into an answer, HttpContent is abstract so you need to use one of the derived classes:

enter

c# – Cant find how to use HttpContent

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/

Leave a Reply

Your email address will not be published.