Rudy M Rudy M - 2 months ago 20
ASP.NET (C#) Question

HttpResponseMessage Compression Issue

I have a web application written in ASP.NET. All is working okay, except that I would like to compress the data being returned. The data is basically a List of custom models. Currently I do something like:

string json_string = new JavaScriptSerializer().Serialize(my_models);

using (var output = new MemoryStream())
{
using (var compressor = new Ionic.Zlib.GZipStream(output, Ionic.Zlib.CompressionMode.Compress, Ionic.Zlib.CompressionLevel.BestCompression))
{
compressor.Write(Encoding.ASCII.GetBytes(json_string), 0, json_string.Length);
}
}


I then proceed with the following:

HttpResponseMessage json = Request.CreateResponse(HttpStatusCode.OK, json_string);

json.Content.Headers.Add("content-encoding", "gzip");


This causes an application error. In Chrome (through the console), I see the following message:

ERR_CONTENT_DECODING_FAILED

Where am I going wrong here? Thanks!

Answer

So in your code you wrote the compressed content to your MemoryStream but your json_string is still your original json_string which then you added that original string as response but marked it as compressed gzip format.

So in the end Chrome tries to decode a pure string JSON content with gzip and it failed to do so

You would want to write whats inside output into json_string object before sending it off

Or you can config IIS to always compress everything to save yourself some trouble.

Comments