MVC 开启gzip压缩
1 using System.IO; 2 using System.IO.Compression; 3 using System.Web; 4 using System.Web.Mvc; 5 6 public class CompressAttribute : ActionFilterAttribute 7 { 8 public override void OnResultExecuted(ResultExecutedContext filterContext) 9 { 10 //如果出现错误,则不进行压缩,否则页面会出现乱码,而不是报错的黄页 11 if (filterContext.Exception != null) 12 return; 13 14 HttpResponseBase Response = filterContext.HttpContext.Response as HttpResponseBase; 15 16 //判断IIS或者其他承载设备是是否启用了GZip或DeflateStream 17 if (Response.Filter is GZipStream || Response.Filter is DeflateStream) 18 return; 19 20 //开始进入压缩环节 21 string AcceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; 22 if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))) 23 { 24 if (AcceptEncoding.Contains("gzip")) 25 { 26 Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress); 27 Response.Headers.Remove("Content-Encoding"); 28 Response.AppendHeader("Content-Encoding", "gzip"); 29 } 30 else 31 { 32 Response.Filter = new DeflateStream(Response.Filter, CompressionMode.Compress); 33 Response.Headers.Remove("Content-Encoding"); 34 Response.AppendHeader("Content-Encoding", "deflate"); 35 } 36 } 37 } 38 }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。