Drop-in module for ASP.Net WebAPI that enables GZip
and Deflate
support.
This module is based on this blog post by Ben Foster which in turn is based on this blog post by Kiran Challa.
This code improves on their work by adding several new options, as well as fixing some issues with the original code.
Package | Version | Downloads |
---|---|---|
Microsoft.AspNet.WebApi.Extensions.Compression.Server | ||
System.Net.Http.Extensions.Compression.Client |
You need to add the compression handler as the last applied message handler on outgoing requests, and the first one on incoming requests.
To do that, just add the following line to your App_Start\WebApiConfig.cs
file after adding all your other message handlers:
GlobalConfiguration.Configuration.MessageHandlers.Insert(0, new ServerCompressionHandler(new GZipCompressor(), new DeflateCompressor()));
This will insert the ServerCompressionHandler
to the request pipeline as the first on incoming requests, and the last on outgoing requests.
If you are doing your requests with JavaScript
you probably don't have to do do anything.
Just make sure the gzip
and deflate
values are included in the Accept-Encoding
header. (Most browsers do this by default)
You need to apply the following code when creating your HttpClient
.
var client = new HttpClient(new ClientCompressionHandler(new GZipCompressor(), new DeflateCompressor()));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
Thats it! You should now immediately start experiencing smaller payloads when doing GET, POST, PUT, etc.
By default, both ServerCompressionHandler
and ClientCompressionHandler
compress everything larger than 860 bytes
.
However, this can be overriden by inserting a threshold as the first parameter like this:
var serverCompressionHandler = new ServerCompressionHandler(4096, new GZipCompressor(), new DeflateCompressor());
var clientCompressionHandler = new ClientCompressionHandler(4096, new GZipCompressor(), new DeflateCompressor());
The above code will skip compression for any request/response that is smaller than 4096 bytes
/ 4 kB
.
It is possible to disable compression for a specific endpoint. Just add the [Compression(Enabled = false)]
attribute to your endpoint method. (Or the whole controller if you want to disable for all endpoints in it)
When using the OWIN Authentication pipeline, you might encounter errors saying that Server cannot append header after http headers have been sent
. This is a bug with OWIN, but as of this moment it has not been fixed.
The workaround is to install the Microsoft.AspNet.WebApi.Extensions.Compression.Server.Owin package and use the included OwinServerCompressionHandler
instead of the default ServerCompressionHandler
. This class contains code to detect whether the headers have been sent already and prevent any attempts at compression.
ByteArrayContent
from an ApiController