StringContent vs ObjectContent

Lalman picture Lalman · Jun 8, 2015 · Viewed 20.3k times · Source

I am using System.Net.Http's HttpClient to call a REST API with "POST" using the following code:

using (HttpRequestMessage requestMessage = new HttpRequestMessage(
                                           HttpMethod.Post, new Uri(request)) { })
{
     response = await httpClient.PostAsync(request, objectContent);
}

The "objectContent" is currently this -

objectContent = new ObjectContent(jsonContent.GetType(),
                                  jsonContent,
                                  new JsonMediaTypeFormatter());

I was wondering what difference it makes if this was a StringContent rather than an ObjectContent like this?

objectContent = new StringContent(content);
objectContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

Both work fine. Because it is JSON, i tend to assume that StringContent would make sense. But when is ObjectContent to be used because pretty much all content sent is a "string".

Answer

Yuval Itzchakov picture Yuval Itzchakov · Jun 8, 2015

I was wondering what difference it makes if this was a StringContent rather than an ObjectContent like this?

In your example there won't be any difference. ObjectContent simply allows a "wider" range of types to be sent via HttpClient, while StringContent is narrower for string values only, such as JSON.

StringContent is a slim wrapper around ByteArrayContent, and actually stores the value passed as a byte[]. You simply get the benefit of not needing to transform your string back and forth.

Edit:

Given the fact that you're posting a JSON, you can even make it less verbose by using HttpClientExtensions.PostAsJsonAsync<T>:

await httpClient.PostAsJsonAsync(url, json);