1. 程式人生 > >ASP.NET Web API中使用GZIP 或 Deflate壓縮

ASP.NET Web API中使用GZIP 或 Deflate壓縮

== too light class using GZip壓縮 public remove log

對於減少響應包的大小和響應速度,壓縮是一種簡單而有效的方式。

那麽如何實現對ASP.NET Web API 進行壓縮呢,我將使用非常流行的庫用於壓縮/解壓縮稱為DotNetZip庫。這個庫可以使用NuGet包獲取

現在,我們實現了Deflate壓縮ActionFilter。

技術分享圖片
public class DeflateCompressionAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuted(HttpActionExecutedContext actContext)
        {
            var content = actContext.Response.Content;
            var bytes = content == null ? null : content.ReadAsByteArrayAsync().Result;
            var zlibbedContent = bytes == null ? new byte[0] :
            CompressionHelper.DeflateByte(bytes);
            actContext.Response.Content = new ByteArrayContent(zlibbedContent);
            actContext.Response.Content.Headers.Remove("Content-Type");
            actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
            actContext.Response.Content.Headers.Add("Content-Type", "application/json");
            base.OnActionExecuted(actContext);
        }
    }

public class CompressionHelper
    {
        public static byte[] DeflateByte(byte[] str)
        {
            if (str == null)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (
                    var compressor = new Ionic.Zlib.DeflateStream(
                    output, Ionic.Zlib.CompressionMode.Compress,
                    Ionic.Zlib.CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }

                return output.ToArray();
            }
        }
    }
技術分享圖片

使用的時候

   [DeflateCompression]
        public string Get(int id)
        {
            return "ok"+id;
        }

當然如果使用GZIP壓縮的話,只需要將

new Ionic.Zlib.DeflateStream( 改為
new Ionic.Zlib.GZipStream(,然後

actContext.Response.Content.Headers.Add("Content-encoding", "deflate");改為
actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
就可以了,經本人測試,
Deflate壓縮要比GZIP壓縮後的代碼要小,所以推薦使用Deflate壓縮

ASP.NET Web API中使用GZIP 或 Deflate壓縮