.NET MVC 简单实现GZIP
时间:2011-01-20 来源:单程列车
打算用GZIP来做压缩,之前在IIS6上做过,这个项目用MVC做,发现在.NET MVC下有更简单好用的办法来解决:写一个ActionFilter来实现GZIP,优点大家用了就知道,呵呵
public class CompressAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; if (!string.IsNullOrEmpty(acceptEncoding)) { acceptEncoding = acceptEncoding.ToLower(); var response = filterContext.HttpContext.Response; if (acceptEncoding.Contains("gzip")) { response.AppendHeader("Content-encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); } else if (acceptEncoding.Contains("deflate")) { response.AppendHeader("Content-encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); } } } }
用法:
[Longin] [Compress] public ActionResult Index() { return View(); }
只要在打算用GZIP压缩的Action上写上[Compress]就OK了,是不是很简单,呵呵~
相关阅读 更多 +