有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持。在WebAPI请求的资源越大时,使用压缩对性能提升的效果越明显,而当请求的资源很小时则不需要使用压缩和解压,因为压缩和解压同样也是需要耗费一定的时间的。

看见老外写了一篇ASP.NET Web API GZip compression ActionFilter with 8 lines of code

说实话被这标题吸引了,8行代码实现GZip压缩过滤器,我就照着他的去实践了一番,发现居然中文出现乱码。

按照他的实现方式:

1、下载DotNetZipLib

2、解压后添加Ionic.Zlib.dll的dll引用

3、新建DeflateCompression特性和GZipCompression特性,分别代表Deflate压缩和GZip压缩,这两种压缩方式的实现代码很相似

不同的地方就是

actContext.Response.Content.Headers.Add("Content-encoding", "gzip");

actContext.Response.Content.Headers.Add("Content-encoding", "deflate");

  var compressor = new DeflateStream(
output, CompressionMode.Compress,
CompressionLevel.BestSpeed)
 var compressor = new GZipStream(
output, CompressionMode.Compress,
CompressionLevel.BestSpeed)
using System.Net.Http;
using System.Web.Http.Filters; namespace WebAPI.Filter
{
public class GZipCompressionAttribute : 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.GZipByte(bytes);
actContext.Response.Content = new ByteArrayContent(zlibbedContent);
actContext.Response.Content.Headers.Remove("Content-Type");
actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
actContext.Response.Content.Headers.Add("Content-Type", "application/json");
base.OnActionExecuted(actContext);
}
}
}
using System.Net.Http;
using System.Web.Http.Filters; namespace WebAPI.Filter
{
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);
}
}

4、添加一个压缩帮助类CompressionHelper

using System.IO;
using Ionic.Zlib; namespace WebAPI.Filter
{
public class CompressionHelper
{
public static byte[] DeflateByte(byte[] str)
{
if (str == null)
{
return null;
} using (var output = new MemoryStream())
{
using (
var compressor = new DeflateStream(
output, CompressionMode.Compress,
CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
} return output.ToArray();
}
}
public static byte[] GZipByte(byte[] str)
{
if (str == null)
{
return null;
}
using (var output = new MemoryStream())
{
using (
var compressor = new GZipStream(
output, CompressionMode.Compress,
CompressionLevel.BestSpeed))
{
compressor.Write(str, 0, str.Length);
} return output.ToArray();
}
}
}
}

5、控制器调用,这里我写的测试代码:

    public class TestController : ApiController
{
StringBuilder sb = new StringBuilder(); [GZipCompression]
public string Get(int id)
{
for (int i = 0; i < 1000;i++ )
{
sb.Append("这里是中国的领土" + i);
}
return sb.ToString() + DateTime.Now.ToLocalTime() + "," + id;
}
}

先看下不使用压缩,注释//[GZipCompression] 标记,文件大小是26.4kb,请求时间是1.27s

使用[GZipCompression]标记,添加压缩后,文件大小是2.4kb,响应时间是1.21,Respouse Body明显小了很多,但是响应时间少得并不明显,因为在本地环境下载太快了,而压缩解压却要消耗一定的时间,界面加载的时间主要消耗在onload上了。有个问题:中文显示乱码了。

使用.net自带的压缩,在System.IO.Compression中提供了对应的类库——GZipStream与DeflateStream。控制器调用代码不变,新建一个CompressContentAttribute.cs类,代码如下:

using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters; namespace WebAPI.Filter
{
// <summary>
/// 自动识别客户端是否支持压缩,如果支持则返回压缩后的数据
/// Attribute that can be added to controller methods to force content
/// to be GZip encoded if the client supports it
/// </summary>
public class CompressContentAttribute : ActionFilterAttribute
{
/// <summary>
/// Override to compress the content that is generated by
/// an action method.
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(HttpActionContext filterContext)
{
GZipEncodePage();
} /// <summary>
/// Determines if GZip is supported
/// </summary>
/// <returns></returns>
public static bool IsGZipSupported()
{
string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
if (!string.IsNullOrEmpty(AcceptEncoding) &&
(AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))
return true;
return false;
} /// <summary>
/// Sets up the current page or handler to use GZip through a Response.Filter
/// IMPORTANT:
/// You have to call this method before any output is generated!
/// </summary>
public static void GZipEncodePage()
{
HttpResponse Response = HttpContext.Current.Response; if (IsGZipSupported())
{
string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"]; if (AcceptEncoding.Contains("deflate"))
{
Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
System.IO.Compression.CompressionMode.Compress);
#region II6不支持此方法,(实际上此值默认为null 也不需要移除)
//Response.Headers.Remove("Content-Encoding");
#endregion
Response.AppendHeader("Content-Encoding", "deflate");
}
else
{
Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
System.IO.Compression.CompressionMode.Compress);
#region II6不支持此方法,(实际上此值默认为null 也不需要移除)
//Response.Headers.Remove("Content-Encoding");
#endregion
Response.AppendHeader("Content-Encoding", "gzip");
}
} // Allow proxy servers to cache encoded and unencoded versions separately
Response.AppendHeader("Vary", "Content-Encoding");
}
} /// <summary>
/// 强制Defalte压缩
/// Content-encoding:gzip,Content-Type:application/json
/// DEFLATE是一个无专利的压缩算法,它可以实现无损数据压缩,有众多开源的实现算法。
/// </summary>
public class DeflateCompressionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext filterContext)
{
HttpResponse Response = HttpContext.Current.Response;
Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
System.IO.Compression.CompressionMode.Compress);
#region II6不支持此方法,(实际上此值默认为null 也不需要移除)
//Response.Headers.Remove("Content-Encoding");
#endregion
Response.AppendHeader("Content-Encoding", "deflate");
}
} /// <summary>
/// 强制GZip压缩,application/json
/// Content-encoding:gzip,Content-Type:application/json
/// GZIP是使用DEFLATE进行压缩数据的另一个压缩库
/// </summary>
public class GZipCompressionAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext filterContext)
{
HttpResponse Response = HttpContext.Current.Response;
Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
System.IO.Compression.CompressionMode.Compress);
#region II6不支持此方法,(实际上此值默认为null 也不需要移除)
//Response.Headers.Remove("Content-Encoding");
#endregion
Response.AppendHeader("Content-Encoding", "gzip");
}
}
}

运行查看结果,压缩能力比DotNetZipLib略差,但是不再出现乱码了。

把控制器代码中的标记改为   [DeflateCompression],使用Deflate压缩再来看下效果:

Deflate压缩后,Content-Length值为2538,而GZip压缩Content-Length值为2556,可见Deflate压缩效果更好。

这里,WebAPI的压缩我都是通过Action过滤器的方式来实现,当然你也可以写在WebAPI中的全局配置中,考虑到有些API接口并不需要使用到压缩,所以就通过Action过滤器的方式来实现了。

dudu的这篇文章HttpClient与APS.NET Web API:请求内容的压缩与解压在客户端压缩、在服务端解压。

最新文章

  1. 移动手机端H5无缝间歇平滑向上滚动js代码
  2. 我的SpringMVC配置
  3. angularjs jquery thinkPHP3.2.3 相结合小实例
  4. php基础32:正则匹配-修饰符
  5. Linux系统排查1——内存篇
  6. 第三回 Bootstrap3.x 起步
  7. ASP.NET jQuery 随笔 从DropDownList获取选择的text和value值
  8. 网络编程应用:基于UDP协议【实现聊天程序】--练习
  9. CENTOS6.6上搭建单实例ORACLE12C
  10. BUNOJ 1011
  11. 责任链模式-Chain of Responsibility(Java实现), 例1
  12. 关于Java多线程的一些常考知识点
  13. Codeforces980 D. Perfect Groups
  14. 13)django-ORM(连表一对多,外键创建,创建数据,3种查询)
  15. MIDAS.dll 出错时 (Error loading MIDAS.DLL.)
  16. happens-before
  17. 【11.8校内测试】【倒计时2天】【状压DP】【随机化?/暴力小模拟】
  18. 转发-基于ASP.NET MVC 4/5 Razor的模块化/插件式架构实现
  19. 理解 Redis(1) - Redis 简介
  20. Android-WebView与本地HTML(播放视频)

热门文章

  1. Codeforces Round #514 (Div. 2) C. Sequence Transformation 思维构造
  2. TP5调用微信JSSDK 教程 - 测试成功案例
  3. MT【293】拐点处切线
  4. 【bfs】Knight Moves
  5. cf1073G Yet Another LCP Problem (SA+权值线段树)
  6. 利用httpd配置虚拟目录创建下载站点
  7. pre标签内文本自动换行
  8. C# 中Web.config文件的读取与写入
  9. django 通过ajax完成邮箱用户注册、激活账号
  10. IO处理要注意的事:关闭资源!关闭资源!关闭资源!