/// <summary>
/// 文件压缩特性
/// </summary>
public class CompressFilterAttribute : ActionFilterAttribute
{
private bool isEnableCompression = true; /// <summary>
/// 构造函数
/// </summary>
public CompressFilterAttribute()
{
} #region OnActionExecuting
/// <summary>
/// Action方法执行前执行的方法
/// </summary>
/// <param name="filterContext">ActionExecutingContext 对象</param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.IsDefined(typeof(NoCompress), false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoCompress), false))
{
this.isEnableCompression = false;
}
}
#endregion #region OnResultExecuted
/// <summary>
/// 返回结果集之后执行的方法
/// </summary>
/// <param name="filterContext">结果执行上下文</param>
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
return;
} if (filterContext.Exception != null)
{
return;
} if (this.isEnableCompression)
{
HttpRequestBase request = filterContext.HttpContext.Request;
HttpResponseBase response = filterContext.HttpContext.Response;
string acceptEncoding = request.Headers["Accept-Encoding"]; if (acceptEncoding == null)
{
return;
} if (acceptEncoding.ToLower().Contains("gzip"))
{
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.ToLower().Contains("deflate"))
{
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
response.AppendHeader("Content-Encoding", "deflate");
}
}
#endregion
}
}
文件压缩特性和排除文件压缩特性的完美结合,相信可以让你满足需求。
排除文件压缩特性:NoCompress
/// <summary>
/// 不启用压缩特性
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class NoCompress : Attribute
{
}