压缩请求数据(优化页面加载太慢之一)
1 /// <summary> 2 /// 允许压缩 3 /// </summary> 4 public class AllowCompressAttribute : System.Web.Mvc.ActionFilterAttribute 5 { 6 /// <summary> 7 /// 压缩方法 8 /// </summary> 9 public override void OnResultExecuting(ResultExecutingContext filterContext) 10 { 11 string acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; 12 if (String.IsNullOrEmpty(acceptEncoding)) return; 13 var response = filterContext.HttpContext.Response; 14 acceptEncoding = acceptEncoding.ToUpperInvariant(); 15 //查看客户端是否支持压缩 16 if (acceptEncoding.Contains("GZIP")) 17 { 18 response.AppendHeader("Content-Encoding", "gzip"); 19 response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); 20 } 21 else if (acceptEncoding.Contains("DEFLATE")) 22 { 23 response.AppendHeader("Content-Encoding", "deflate"); 24 response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); 25 } 26 base.OnResultExecuting(filterContext); 27 } 28 }