淘先锋技术网

首页 1 2 3 4 5 6 7
 1     /// <summary>
 2     /// 文件压缩特性
 3     /// </summary>
 4     public class CompressFilterAttribute : ActionFilterAttribute
 5     {
 6         private bool isEnableCompression = true;
 7 
 8         /// <summary>
 9         /// 构造函数
10         /// </summary>
11         public CompressFilterAttribute()
12         {
13         }
14 
15         #region OnActionExecuting
16         /// <summary>
17         /// Action方法执行前执行的方法
18         /// </summary>
19         /// <param name="filterContext">ActionExecutingContext 对象</param>
20         public override void OnActionExecuting(ActionExecutingContext filterContext)
21         {
22             if (filterContext.ActionDescriptor.IsDefined(typeof(NoCompress), false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(NoCompress), false))
23             {
24                 this.isEnableCompression = false;
25             }
26         }
27         #endregion
28 
29         #region OnResultExecuted
30         /// <summary>
31         /// 返回结果集之后执行的方法
32         /// </summary>
33         /// <param name="filterContext">结果执行上下文</param>
34         public override void OnResultExecuted(ResultExecutedContext filterContext)
35         {
36             if (filterContext.HttpContext.Request.IsAjaxRequest())
37             {
38                 return;
39             }
40 
41             if (filterContext.Exception != null)
42             {
43                 return;
44             }
45 
46             if (this.isEnableCompression)
47             {
48                 HttpRequestBase request = filterContext.HttpContext.Request;
49                 HttpResponseBase response = filterContext.HttpContext.Response;
50                 string acceptEncoding = request.Headers["Accept-Encoding"];
51 
52                 if (acceptEncoding == null)
53                 {
54                     return;
55                 }
56 
57                 if (acceptEncoding.ToLower().Contains("gzip"))
58                 {
59                     response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
60                     response.AppendHeader("Content-Encoding", "gzip");
61                 }
62                 else if (acceptEncoding.ToLower().Contains("deflate"))
63                 {
64                     response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
65                     response.AppendHeader("Content-Encoding", "deflate");
66                 }
67             }
68         #endregion
69         }
70     }

文件压缩特性和排除文件压缩特性的完美结合,相信可以让你满足需求。

排除文件压缩特性:NoCompress

1   /// <summary>
2     /// 不启用压缩特性
3     /// </summary>
4     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
5     public sealed class NoCompress : Attribute 
6     {
7     }

 

 

转载于:https://www.cnblogs.com/yangda/p/3166448.html