我如何从ASP.NET MVC中的JsonResult操作返回gzip json?

时间:2013-10-19 08:23:49

标签: c# asp.net-mvc json iis-7 gzip

我在IIS 7.5 Web服务器上正确设置了gzip,并且在大多数情况下都能正常工作。

但我可以看到响应标头显示我对JsonResult方法发出的任何请求都没有被gzip压缩。我需要更改什么,以便JsonResult使用Content-Encoding返回数据:gzip?

这是调用JsonResult方法时标题的屏幕截图:

enter image description here

与调用返回html的内容时的标题截图相比,例如RenderPartial():

enter image description here

编辑:这些是来自applicationHost.config的压缩设置:

    <httpCompression 
        directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
        <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
        <dynamicTypes>
            <add mimeType="text/*" enabled="true" />
            <add mimeType="application/json" enabled="true" />
            <add mimeType="application/json; charset=utf-8" enabled="true" />                
            <add mimeType="message/*" enabled="true" />
            <add mimeType="application/x-javascript" enabled="true" />
            <add mimeType="*/*" enabled="false" />
        </dynamicTypes>
        <staticTypes>
            <add mimeType="text/*" enabled="true" />
            <add mimeType="message/*" enabled="true" />
            <add mimeType="application/json" enabled="true" />
            <add mimeType="application/json; charset=utf-8" enabled="true" />                
            <add mimeType="application/x-javascript" enabled="true" />
            <add mimeType="application/atom+xml" enabled="true" />
            <add mimeType="application/xaml+xml" enabled="true" />
            <add mimeType="*/*" enabled="false" />
        </staticTypes>
    </httpCompression>

2 个答案:

答案 0 :(得分:1)

请确保位于%WinDir%\ System32 \ inetsrv \ config \ applicationHost.config 的IIS applicationHost.config文件包含以下代码块。

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

答案 1 :(得分:0)

您的配置看起来是正确的。可能是您没有达到IIS开始压缩所有内容的阈值。

试试这个: 在IIS管理器中,转到配置编辑器,然后找到system.WebServer / serverRuntime。 查看frequentHitThreshold和frequentHitTimePeriod设置,然后将其删除以确保在测试时达到阈值。

这里有更多阅读: http://blogs.msdn.com/b/asiatech/archive/2013/02/19/unable-to-compress-json-result-in-iis-7-x.aspx