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.