Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringContent vs ObjectContent

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".

like image 952
Lalman Avatar asked Jun 08 '15 08:06

Lalman


1 Answers

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);
like image 189
Yuval Itzchakov Avatar answered Oct 14 '22 08:10

Yuval Itzchakov