I'm developing an ASP.NET Web Api 2.2 application with .NET Framework 4.5, C# and Newtonsoft.Json 6.0.8.
I have this method to post to this web api:
protected bool Post<T>(string completeUri, ref T dataToPost)
{
bool result = false;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(_webApiHost);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(JsonConvert.SerializeObject(dataToPost), Encoding.UTF8, "application/json");
Task<HttpResponseMessage> response = client.PostAsync(completeUri, content);
[ ... ]
}
return result;
}
When I have a lot of data to send I get an Out of Memory exception here:
HttpContent content = new StringContent(JsonConvert.SerializeObject(dataToPost), Encoding.UTF8, "application/json");
I have read a lot about compression but I don't know which one do I have to use. I don't know if there are more types but I have found two kinds: IIS compression and GZip compression.
Which one do I have to use? If I use GZip compression, do I have to modify my web api client?
UPDATE:
I have this class to serialize but I haven't used it:
public static string Serialize(Models.Aggregations aggregation)
{
if (aggregation == null)
throw new ArgumentNullException("aggregation");
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("Code");
writer.WriteValue(aggregation.Code);
if (!string.IsNullOrWhiteSpace(aggregation.Created))
{
writer.WritePropertyName("Created");
writer.WriteValue(aggregation.Created);
}
writer.WriteEndObject();
return sw.ToString();
}
It will solve the problem if I use it? I ask this because @CodeCaster has suggested me to use JsonTextWriter
but I don't know how to use it inside my post method.
UPDATE 2
Following @CodeCaster recommendation I'm trying to optimize how I send data to that Web Api and I'm writing my own JSON serializer with this class:
public static string Serialize(Models.Aggregations aggregation)
{
if (aggregation == null)
throw new ArgumentNullException("aggregation");
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteStartObject();
writer.WritePropertyName("Code");
writer.WriteValue(aggregation.Code);
if (!string.IsNullOrWhiteSpace(aggregation.Created))
{
writer.WritePropertyName("Created");
writer.WriteValue(aggregation.Created);
}
writer.WriteEndObject();
return sw.ToString();
}
But @CodeCaster has told me that to make it more efficient I will need to write as a Stream into StreamContent
using JsonTextWriter
.
But I don't know how to do that because I don't know how to instantiate StreamContent
. All the examples that I've seen use a var stream
but I don't see how they instantiate that object.
How can I use JsonTextWriter to write into the stream?