MVC全局过滤器-流压缩输出

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文件中进行注册即可

    /// 
    /// 默认过滤器
    /// 
    public class FilterConfig
    {
        /// 
        /// 注册过滤器
        /// 
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            ...
            filters.Add(new GZipCompressAttribute());
        }
    }

然后global.cs文件中注入

...
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
...

 

你可能感兴趣的:(MVC)