问题
我在IIS 7.5上运行的MVC 4应用程序上有一个Telerik MVC UI网格,可以通过AJAX潜在地返回大量的JSON数据,在极端情况下为800kb或更多.由于有效载荷可能很大,我想要GZIP它.对于我的生活,我不能让它工作.
控制器的动作是:
public ActionResult _CustomBinding([DataSourceRequest] DataSourceRequest request,SearchMemberModel search) { //Do some stuff return Json(result); }
Fiddler报告:
已经尝试了
我已经确保在IIS中启用动态和静态压缩:
App Web.Config修改:
<system.webServer> <serverRuntime frequentHitThreshold="1" frequentHitTimePeriod="10:00:00" /> <validation validateIntegratedModeConfiguration="false" /> <modules runAllManagedModulesForAllRequests="false"> <remove name="FormsAuthentication" /> </modules> <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files"> <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" /> <dynamicTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" enabled="true" /> <add mimeType="application/x-javascript" enabled="true" /> <add mimeType="application/json" enabled="true" /> <add mimeType="*/*" enabled="false" /> </dynamicTypes> <staticTypes> <add mimeType="text/*" enabled="true" /> <add mimeType="message/*" 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> <urlCompression doStaticCompression="true" doDynamicCompression="true" /> </system.webServer>
我确定了ApplicationHost file has the right mime types:
<add mimeType="application/json" enabled="true" /> <add mimeType="application/json; charset=utf-8" enabled="true" /> <add mimeType="application/json;charset=utf-8" enabled="true" />
我已经尝试了serverRuntime频繁HitThreshold需要修改的suggestion here.
有没有我失踪的东西?
解决方法
好吧,我似乎也需要在我的控制器里做一些事情:
根据以下提取自:how to gzip content in asp.net MVC?
public class CompressAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(encodingsAccepted)) return; encodingsAccepted = encodingsAccepted.ToLowerInvariant(); var response = filterContext.HttpContext.Response; if (encodingsAccepted.Contains("deflate")) { response.AppendHeader("Content-encoding","deflate"); response.Filter = new DeflateStream(response.Filter,CompressionMode.Compress); } else if (encodingsAccepted.Contains("gzip")) { response.AppendHeader("Content-encoding","gzip"); response.Filter = new GZipStream(response.Filter,CompressionMode.Compress); } }
控制器中的使用:
[Compress] public class BookingController : BaseController {...}