基于代码的页面压缩

压缩过滤器:

 1 public class CompressFilter : ActionFilterAttribute
 2     {
 3         public override void OnActionExecuting(ActionExecutingContext filterContext)
 4         {
 5             HttpRequestBase request = filterContext.HttpContext.Request;
 6 
 7             string acceptEncoding = request.Headers["Accept-Encoding"];
 8 
 9             if (string.IsNullOrEmpty(acceptEncoding)) return;
10 
11             acceptEncoding = acceptEncoding.ToUpperInvariant();
12 
13             HttpResponseBase response = filterContext.HttpContext.Response;
14 
15             if (acceptEncoding.Contains("GZIP"))
16             {
17                 response.AppendHeader("Content-encoding", "gzip");
18                 response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
19             }
20             else if (acceptEncoding.Contains("DEFLATE"))
21             {
22                 response.AppendHeader("Content-encoding", "deflate");
23                 response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
24             }
25         }
26     }

调用:

1      [CompressFilter]
2         public ActionResult Index()
3         {
4             ViewData["Message"] = "欢迎使用 ASP.NET MVC!";
5 
6             return View();
7         }

 

 

posted @ 2012-09-18 11:23  鸿bi  阅读(219)  评论(0编辑  收藏  举报