MVCオープンgzip圧縮

6474 ワード

 1     using System.IO;

 2     using System.IO.Compression;

 3     using System.Web;

 4     using System.Web.Mvc;

 5 

 6     public class CompressAttribute : ActionFilterAttribute

 7     {

 8         public override void OnResultExecuted(ResultExecutedContext filterContext)

 9         {

10             // , , , 

11             if (filterContext.Exception != null)

12                 return;

13 

14             HttpResponseBase Response = filterContext.HttpContext.Response as HttpResponseBase;

15 

16             // IIS GZip DeflateStream

17             if (Response.Filter is GZipStream || Response.Filter is DeflateStream)

18                 return;

19 

20             // 

21             string AcceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];

22             if (!string.IsNullOrEmpty(AcceptEncoding) && (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))

23             {

24                 if (AcceptEncoding.Contains("gzip"))

25                 {

26                     Response.Filter = new GZipStream(Response.Filter, CompressionMode.Compress);

27                     Response.Headers.Remove("Content-Encoding");

28                     Response.AppendHeader("Content-Encoding", "gzip");

29                 }

30                 else

31                 {

32                     Response.Filter = new DeflateStream(Response.Filter, CompressionMode.Compress);

33                     Response.Headers.Remove("Content-Encoding");

34                     Response.AppendHeader("Content-Encoding", "deflate");

35                 }

36             }

37         }

38     }