Randy Minder
Randy Minder

Reputation: 48402

How to enable HTTP compression to compress JSON documents

I have an MVC 5 application (C#) hosted on Microsoft Azure. The app returns some fairly large JSON documents from the server to the client. Does anyone know how to turn HTTP compression on so that these documents are compressed going to the client? I've Googled this but I couldn't find anything that wasn't at least 3-4 years old.

I suppose an alternative would be to compress just the JSON document using a compression utility. I've tried LZ-String but I can't seem to be able to compress the document on the server using the C# version and decompress on the client using the JavaScript version, and have the resulting JSON document be recognized.

Upvotes: 2

Views: 8559

Answers (1)

astaykov
astaykov

Reputation: 30903

To enable compression of JsonResult of your MVC Controller's actions you need to enable dynamic compression from web.config file:

  <system.webServer>
    <urlCompression doDynamicCompression="true" />
    <httpCompression>
      <dynamicTypes>
        <add mimeType="application/json" enabled="true" />
        <add mimeType="application/json; charset=utf-8" enabled="true" />       
      </dynamicTypes>
    <staticTypes>
        <add mimeType="application/json" enabled="true" />
        <add mimeType="application/json; charset=utf-8" enabled="true" />       
    </staticTypes>
    </httpCompression>
  </system.webServer>  

A working example with exact above configuration is published on free tier of Azure WebSites and can be tested with simple HTTP GET request:

GET https://double.azurewebsites.net/Home/SomeJson HTTP/1.1
User-Agent: Fiddler
Accept-Encoding: gzip, compress
Host: double.azurewebsites.net

Note, that Accept-Encoding header is absolute must to trigger server side compression. Please also note the mime type application/json; charset=utf-8 which is the mime type served by the ASP.NET MVC5 JsonResult.

Upvotes: 14

Related Questions