当前位置:首页 > Windows程序 > 正文

ASP.NET Web API中使用GZIP 或 Deflate压缩

2024-03-31 Windows程序

对付减少响应包的巨细和响应速度,压缩是一种简单而有效的方法。

那么如何实现对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压缩

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/33993.html

Jm-杰米博客Jamie
草根站长的技术交流乐园!IT不会不要紧快来好好学习吧!
  • 20786文章总数
  • 7494587访问次数
  • 建站天数
  • 友情链接