WebAPI的压缩
有时候为了提升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[] :
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[] :
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, , 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, , str.Length);
} return output.ToArray();
}
}
}
}
5、控制器调用,这里我写的测试代码:
public class TestController : ApiController
{
StringBuilder sb = new StringBuilder(); [GZipCompression]
public string Get(int id)
{
for (int i = ; i < ;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:请求内容的压缩与解压在客户端压缩、在服务端解压。
WebAPI的压缩的更多相关文章
- Asp.net WebAPi gzip压缩和json格式化
现在webapi越来越流行了,很多时候它都用来做接口返回json格式的数据,webapi原本是根据客户端的类型动态序列化为json和xml的,但实际很多时候我们都是序列化为json的,所以webapi ...
- asp.net core系列 77 webapi响应压缩
一.介绍 背景:目前在开发一个爬虫框架,使用了.net core webapi接口作为爬虫调用入口,在调用 webapi时发现爬虫耗时很短(1秒左右),但客户端获取响应时间却在3~4秒.对于这个问题考 ...
- webapi使用压缩
支持GZIP.DEFLATE压缩 /// <summary> /// Gzip 压缩 /// </summary> public sealed class Compressio ...
- WebAPI性能优化之压缩解压
有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持.在WebAPI请求的资源越大时,使用压缩对性能提升的效果越明显,而当请求的资源很小 ...
- WebAPI性能优化
WebAPI性能优化之压缩解压 有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持.在WebAPI请求的资源越大时,使用压缩对性能提升 ...
- .NET压缩图片保存 .NET CORE WebApi Post跨域提交 C# Debug和release判断用法 tofixed方法 四舍五入 (function($){})(jQuery); 使用VUE+iView+.Net Core上传图片
.NET压缩图片保存 需求: 需要将用户后买的图片批量下载打包压缩,并且分不同的文件夹(因:购买了多个用户的图片情况) 文章中用到了一个第三方的类库,Nuget下载 SharpZipLib 目前用 ...
- webapi 开启gzip压缩
1.nuget安装Microsoft.AspNet.WebApi.Extensions.Compression.Server 2.global.asax.cs里引用System.Net.Http.Ex ...
- WebApi Gzip(Deflate) 压缩请求数据
由于不能直接访问指定数据库,只能通过跳板机查询Oracle数据,所以要做一个数据中转接口, 查询数据就要压缩,于是就找资料,代码如下,其中要注意的是Response.Headers.Remove(&q ...
- 如何在 webApi 当中接收 Gzip 压缩或者加密后的 请求消息内容!
今天在上班的时候遇到个问题,移动端要求我们用GZIP加密.当时一想着多简单,但是在做的时候发现个问题. 就是移动端Post到 服务端的数据也是经过 Gzip的,并不是单一的像网站那样只针对网页进行 压 ...
随机推荐
- 高德地图教程_poi搜索和显示
通过高仿深圳的应用近期打算.UI我们已经做了,我见过APP查询界面.关闭网络也将是能够查询其指示数据被存储在数据库中,或者是第一网络,所有网站上的数据是好了.我想简单地使用查询地图提供了. 曾经是接触 ...
- Java 实现迭代器(Iterator)模式
类图 /** * 自己定义集合接口, 相似java.util.Collection * 用于数据存储 * @author stone * */ public interface ICollection ...
- [探索]点点轻博客搬家到WordPress(一)
摘要:点点博客备份XML通过DiandianToWordpress-beta.sh(文末给出)搬家到Wordpress博客 本人曾使用过点点轻博客,也深知像点点博客,Lofter博客导出的XML文件不 ...
- Spring IOC 之Bean作用域
当你创建一个bean定义的时候,你创建了一份通过那种bean定义的bean的创建类的真正实力的处方.bean的定义是一个处方 的想法是很重要的的.因为这意味着,对于一个类你可以创建很多对象实例从一个单 ...
- leetcode[73] Set Matrix Zeroes 将矩阵置零
给定一个矩阵,把零值所在的行和列都置为零.例如: 1 2 3 1 3 1 1 1 操作之后变为 1 3 0 0 0 1 1 方法1: 赋值另存一个m*n的矩阵,在原矩阵为零的值相应置新的矩阵行和列为零 ...
- 使用OpenWrt的SDK
原文:http://wiki.openwrt.org/doc/howto/obtain.firmware.sdk 为什么要使用SDK: Reasons for using the SDK are: C ...
- 熔断器C#实现
关键词1:保险丝.电闸跳闸.输入密码错误3次则在指定的时间之内禁止登录 关键词2:保护性架构.防御性代码.软件可靠性 实现:https://github.com/fecktty/Circuit_Bre ...
- SQL Server 增删改
--use用来设置当前使用哪个数据库use StudentDb--go批处理go --T-SQL中不区分大小写,数据库表中的数据是区分大小写的--例如:insert与INSERT不区分大小写,数据库表 ...
- Yeoman入门之安装及环境配置
Yeoman入门之安装及环境配置 http://blog.csdn.net/panlingfan/article/details/27345037 http://www.nodejs.orgYEOMA ...
- 逐步在Windows上结合CopSSH + msysGit安装安装Git Server同时集成Git使用Visual Studio
v\:* {behavior:url(#default#VML);} o\:* {behavior:url(#default#VML);} w\:* {behavior:url(#default#VM ...