zoukankan      html  css  js  c++  java
  • ASP.NET Web API中使用GZIP 或 Deflate压缩

    对于减少响应包的大小和响应速度,压缩是一种简单而有效的方式。

    那么如何实现对ASP.NET Web API 进行压缩呢,我将使用非常流行的库用于压缩/解压缩称为DotNetZip库。这个库可以使用NuGet包获取

    现在,我们实现了Deflate压缩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);
            }
        }
    
    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();
                }
            }
        }
    复制代码

    使用的时候

       [DeflateCompression]
            public string Get(int id)
            {
                return "ok"+id;
            }

    当然如果使用GZIP压缩的话,只需要将

    new Ionic.Zlib.DeflateStream( 改为
    new Ionic.Zlib.GZipStream(,然后

    actContext.Response.Content.Headers.Add("Content-encoding", "deflate");改为
    actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
    就可以了,经本人测试,
    Deflate压缩要比GZIP压缩后的代码要小,所以推荐使用Deflate压缩
  • 相关阅读:
    查看eclipse的安装路径
    js中Number()、parseInt()和parseFloat()的区别进行详细介绍
    JSON 基础学习1
    Jquery Math ceil()、floor()、round()比较与用法
    easyui获取当前点击对象tabs的title和Index
    java中String,int,Integer,char、double类型转换
    DNA排序
    The Peanuts
    牛的选举——取最大k个数
    数据筛选——第k小的数
  • 原文地址:https://www.cnblogs.com/lhxsoft/p/8663142.html
Copyright © 2011-2022 走看看