ASP.NET Web API GZip

来源:互联网 发布:php生成word文档 编辑:程序博客网 时间:2024/05/17 13:09

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.

publicclass DeflateCompressionAttribute : ActionFilterAttribute
{
 
   publicoverride void OnActionExecuted(HttpActionExecutedContext actContext)
   {
       varcontent = actContext.Response.Content;
       varbytes = content == null? null: content.ReadAsByteArrayAsync().Result;
       varzlibbedContent = bytes == null? newbyte[0] :
       CompressionHelper.DeflateByte(bytes);
       actContext.Response.Content = newByteArrayContent(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.

publicclass CompressionHelper
{
        publicstatic byte[] DeflateByte(byte[] str)
        {
            if(str == null)
            {
                returnnull;
            }
 
            using(varoutput = newMemoryStream())
            {
                using(
                    varcompressor = newIonic.Zlib.DeflateStream(
                    output, Ionic.Zlib.CompressionMode.Compress,
                    Ionic.Zlib.CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }
 
                returnoutput.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 :

publicclass V1Controller : ApiController
{
   
    [DeflateCompression]
    publicHttpResponseMessage GetCustomers()
    {
 
    }
 
}

 

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

 

0 0
原创粉丝点击