ASP.NET Web API GZip
来源:互联网 发布:php生成word文档 编辑:程序博客网 时间:2024/05/17 13:09
Implement ASP.NET Web API GZip compression ActionFilter
For this example with around 8 lines of code I will use very popular library for Compression / Decompression called DotNetZip library .This library can easily be downloaded from NuGet.
Now we implement Deflate compression 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);
}
}
We also need a helper class to perform compression.
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();
}
}
}
For GZipCompressionAttribute implementation is exactly the same. You only need to call GZipStream instead of DeflateStream in helper method implementation.
If we want to mark some method in controller to be Deflated just put this ActionFilter attribute above method like this :
public
class
V1Controller : ApiController
{
[DeflateCompression]
public
HttpResponseMessage GetCustomers()
{
}
}
If you find some better way to perform this please let me know.
0 0
- ASP.NET Web API GZip
- 利用 ActionFilter 为 ASP.NET Web API 添加 GZip 压缩功能
- asp.net web api
- ASP.NET Web API
- asp.net web api
- asp.net web api
- asp.net web api
- 实战 ASP.NET Web API
- ASP.NET Web Api 教程
- ASP.NET Web API详解
- ASP.NET Web API 简介
- ASP.NET WEB API 读书笔记
- ASP.NET Web API 简介
- ASP.NET Web API 简介
- asp.net web api理解
- ASP.NET Web API 简介
- ASP.NET Web API(一)
- asp.net web api实例
- Python中字符串的解压缩
- NSUnknownKeyException
- 80 port system
- Oracle表维护 快速备份删除数据
- UVA 409 Excuses, Excuses! (字符处理)
- ASP.NET Web API GZip
- Netbeans 快捷键
- UVA 10115 Automatic Editing(字符处理)
- cocos编译出错大全集
- 【Leetcode】Binary Tree Level Order Traversal II (Tree Traversal)
- UVA 10815 Andy's First Dictionary(字符处理)
- UVA 644 Immediate Decodability (字符处理)
- 如何解决ubuntu下用wine报-cant-find-mfc42-dll问题
- 【Leetcode】Binary Tree Zigzag Level Order Traversal (Tree Traversal)