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".
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);
If someone will search how to send request by PostAsync in .NET Core 2.1: I did not found PostAsJsonAsync method in HttpClient, but your solution with setting:
objectContent = new StringContent(content);
objectContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
"do the job" perfectly also in .NET Core.
Edit:
Additionally If you want add your own header you can type:
objectContent.Headers.Add("Your header", "Value");
ObjectContent is used to format more complex Mime types using built-in or custom-written formatters. It is OK to use ObjectContent for a simple string as well, it doesn't make much difference except for the performance which (IMHO and not checked) may be better with StringContent, since it may have been optimized specifically for strings