We are developing backend API's using Nancy. Other than hosting it using IIS, we are self-hosting it using Owin. Since Owin does not handle gzip compression automatically (as IIS does), we need to introduce a middleman to handle response/request compression or de-compression. Are there any libraries available already? If there is no libraries available, what is the best way to do it?
1
votes
1 Answers
2
votes
using System.IO.Compression;
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
pipelines.AfterRequest.AddItemToEndOfPipeline(AddGZip);
}
private void AddGZip(NancyContext context)
{
if ((!context.Response.ContentType.Contains("application/json")) || !context.Request.Headers.AcceptEncoding.Any(
x => x.Contains("gzip")) || !CompressResponse(context.Request.Url.ToString())) return;
var jsonData = new MemoryStream();
context.Response.Contents.Invoke(jsonData);
jsonData.Position = 0;
context.Response.Headers["Content-Encoding"] = "gzip";
context.Response.Contents = s =>
{
var gzip = new GZipStream(s, CompressionMode.Compress, true);
jsonData.CopyTo(gzip);
gzip.Close();
};
}