ASP.NET Web API中使用GZIP 或 Deflate压缩
对于减少响应包的大小和响应速度,压缩是一种简单而有效的方式。
那么如何实现对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压缩


浙公网安备 33010602011771号