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);
...