ASP.NET Web API GZip

Implement ASP.NET Web API GZip compression ActionFilter

For this example with around 8 lines of code I will use very popular library for Compression / Decompression called DotNetZip library .This library can easily be downloaded from NuGet.

Now we implement  Deflate compression 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);
      }
  }

 

We also need a helper class to perform compression.

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();
             }
         }
}

 

For GZipCompressionAttribute implementation is exactly the same. You only need to call GZipStream instead of DeflateStream in helper method implementation.

If we want to mark some method in controller to be Deflated just put this ActionFilter attribute above method like this :

public class V1Controller : ApiController
{
   
     [DeflateCompression]
     public HttpResponseMessage GetCustomers()
     {
 
     }
 
}

 

If you find some better way to perform this please let me know.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值