WebAPI性能优化实例

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);
}
}


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 DeflateStream(
output, CompressionMode.Compress))
{
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))
{
compressor.Write(str, 0, str.Length);
}

return output.ToArray();
}
}
}

调用方式 

WebAPI方法前加

【DeflateCompression]】 或 【GZipCompression】

建议使用 【DeflateCompression]】


 

 

上一篇:WCF中常见的报错:The content type text


下一篇:【数据分析面试】字节跳动数据分析面试题(附答案解析)