我们正在使用Nancy开发后端API。除了使用IIS托管它,我们使用Owin自我托管它。由于Owin不会自动处理gzip压缩(如IIS那样),我们需要引入一个中间人来处理响应/请求压缩或解压缩。有没有可用的图书馆?如果没有可用的库,那么最好的方法是什么?
答案 0 :(得分:2)
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();
};
}