首页 > 学院 > 开发设计 > 正文

MVC 开启gzip压缩

2019-11-17 01:25:20
字体:
来源:转载
供稿:网友

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或DeflateStream17             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                 else31                 {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     }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表