MVC全域性過濾器-流壓縮輸出
阿新 • • 發佈:2019-02-12
using System.IO.Compression; using System.Web.Mvc; namespace LK.Web.Helpers { public class GZipCompressAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //base.OnActionExecuting(filterContext); if (filterContext.IsChildAction) { return; } var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(acceptEncoding)) { return; } 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); } } } }
在filterconfig.cs檔案中進行註冊即可
/// <summary> /// 預設過濾器 /// </summary> public class FilterConfig { /// <summary> /// 註冊過濾器 /// </summary> public static void RegisterGlobalFilters(GlobalFilterCollection filters) { ... filters.Add(new GZipCompressAttribute()); } }
然後global.cs檔案中注入
...
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
...