有时候为了提升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的压缩的更多相关文章

  1. Asp.net WebAPi gzip压缩和json格式化

    现在webapi越来越流行了,很多时候它都用来做接口返回json格式的数据,webapi原本是根据客户端的类型动态序列化为json和xml的,但实际很多时候我们都是序列化为json的,所以webapi ...

  2. asp.net core系列 77 webapi响应压缩

    一.介绍 背景:目前在开发一个爬虫框架,使用了.net core webapi接口作为爬虫调用入口,在调用 webapi时发现爬虫耗时很短(1秒左右),但客户端获取响应时间却在3~4秒.对于这个问题考 ...

  3. webapi使用压缩

    支持GZIP.DEFLATE压缩 /// <summary> /// Gzip 压缩 /// </summary> public sealed class Compressio ...

  4. WebAPI性能优化之压缩解压

    有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持.在WebAPI请求的资源越大时,使用压缩对性能提升的效果越明显,而当请求的资源很小 ...

  5. WebAPI性能优化

    WebAPI性能优化之压缩解压 有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持.在WebAPI请求的资源越大时,使用压缩对性能提升 ...

  6. .NET压缩图片保存 .NET CORE WebApi Post跨域提交 C# Debug和release判断用法 tofixed方法 四舍五入 (function($){})(jQuery); 使用VUE+iView+.Net Core上传图片

    .NET压缩图片保存   需求: 需要将用户后买的图片批量下载打包压缩,并且分不同的文件夹(因:购买了多个用户的图片情况) 文章中用到了一个第三方的类库,Nuget下载 SharpZipLib 目前用 ...

  7. webapi 开启gzip压缩

    1.nuget安装Microsoft.AspNet.WebApi.Extensions.Compression.Server 2.global.asax.cs里引用System.Net.Http.Ex ...

  8. WebApi Gzip(Deflate) 压缩请求数据

    由于不能直接访问指定数据库,只能通过跳板机查询Oracle数据,所以要做一个数据中转接口, 查询数据就要压缩,于是就找资料,代码如下,其中要注意的是Response.Headers.Remove(&q ...

  9. 如何在 webApi 当中接收 Gzip 压缩或者加密后的 请求消息内容!

    今天在上班的时候遇到个问题,移动端要求我们用GZIP加密.当时一想着多简单,但是在做的时候发现个问题. 就是移动端Post到 服务端的数据也是经过 Gzip的,并不是单一的像网站那样只针对网页进行 压 ...

随机推荐

  1. Docker运行 Mono

    Docker运行 Mono Docker 是最近相当热门的一个名词,它是一个基于 Linux Container 的轻量化的虚拟技术,而微软也相当积极与 Docker 合作,在 Azure 上支持这个 ...

  2. Spring IOC之基于JAVA的配置

    基础内容:@Bean 和 @Configuration 在Spring中新的支持java配置的核心组件是 @Configuration注解的类和@Bean注解的方法. @Bean注解被用于表明一个方法 ...

  3. MEF简介及简单的Demo

    MEF简介及简单的Demo 文章开始之前,首先简单介绍一下什么是MEF,MEF,全称Managed Extensibility Framework(托管可扩展框架).单从名字我们不难发现:MEF是专门 ...

  4. Oracle中的Union、Union All、Intersect、Minus

    Oracle中的Union.Union All.Intersect.Minus  众所周知的几个结果集集合操作命令,今天详细地测试了一下,发现一些问题,记录备考. 假设我们有一个表Student,包括 ...

  5. 支付宝集成时的InvalidKeySpecException

    近来在集成第三方支付---支付宝,在集成的过程中严格按照支付宝开发者平台所发布的说明文档和Demo,在我的测试机上可以完美的运行,但是在别人的手机无论怎么就是调用不起来,总是弹出"remot ...

  6. Coded UI Test对Webpage进行自动化测试

    如何使用Coded UI Test对Webpage进行自动化测试   在Visual Studio中,Coded UI Test已经不是什么新特性了,较早版本的Visual Studio中就已经有这个 ...

  7. 取xml文件转成List<T>对象的两种方法

    读取xml文件转成List<T>对象的两种方法(附源码)   读取xml文件转成List<T>对象的两种方法(附源码) 读取xml文件,是项目中经常要用到的,所以就总结一下,最 ...

  8. JavaScript插件——弹出框

    (JavaScript插件——弹出框) 前言 阅读之前您也可以到Bootstrap3.0入门学习系列导航中进行查看http://www.cnblogs.com/aehyok/p/3404867.htm ...

  9. C++指针数组和指向指针的指针

    指针数组 定义: 如果一个 数组,其元素均为指针型数据,该数组为指针数组,也就是说,指针数组中的每一个元素相当于一个指针变量,它的值都是地址. 形式: 一维指针数组的定义形式为: int[类型名] * ...

  10. CSS position overflow float 属性 详解

    position  overflow float 几个属性比较容易混淆,写一段代码详解各自具体情况: position在w3school的可能取值: 值 描述 absolute 生成绝对定位的元素,相 ...