對於減小響應包的大小和響應速度,壓縮是一種簡單而有效的方式。json
那麼如何實現對ASP.NET Web API 進行壓縮呢,我將使用很是流行的庫用於壓縮/解壓縮稱爲DotNetZip庫。這個庫能夠使用NuGet包獲取app
如今,咱們實現了Deflate壓縮ActionFilter。ide
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壓縮的話,只須要將spa
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壓縮