简体   繁体   English

在Nancy / Owin中处理gzip压缩

[英]Handling gzip compression in Nancy/Owin

We are developing backend API's using Nancy. 我们正在使用Nancy开发后端API。 Other than hosting it using IIS, we are self-hosting it using Owin. 除了使用IIS托管之外,我们还使用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. 由于Owin不能自动处理gzip压缩(如IIS一样),因此我们需要引入一个中间人来处理响应/请求压缩或解压缩。 Are there any libraries available already? 是否有可用的库? If there is no libraries available, what is the best way to do it? 如果没有可用的库,什么是最好的方法?

    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();
        };
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM