MVC 中对返回的 data 进行压缩
在webAPI 中返回数据,在数据量比较大的情况的下,返回的data 也可能比较大,有时候可能大于1兆,因此对数据进行压缩能极大的提高数据下载到客户端的时间,提高页面的加载速度。
思路: 在web api 中添加 action filter attribute 来实现,我们先看下其定义:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IFilter
{
/// <summary>
/// Occurs before the action method is invoked.
/// </summary>
/// <param name="actionContext">The action context.</param>
public virtual void OnActionExecuting(HttpActionContext actionContext);
/// <summary>
/// Occurs after the action method is invoked.
/// </summary>
/// <param name="actionExecutedContext">The action executed context.</param>
public virtual void OnActionExecuted(HttpActionExecutedContext actionExecutedContext);
/// <summary>
/// Executes the filter action asynchronously.
/// </summary>
///
/// <returns>
/// The newly created task for this operation.
/// </returns>
/// <param name="actionContext">The action context.</param><param name="cancellationToken">The cancellation token assigned for this task.</param><param name="continuation">The delegate function to continue after the action method is invoked.</param>
Task<HttpResponseMessage> IActionFilter.ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation);
}
代码很清晰,关键是两个虚方法 OnActionExecuting(在controller 调用 action方法之前执行),OnActionExecuted( 在controller 调用 action方法之后执行)。
因为我们要对action 执行后的json 进行压缩,所以我们只需要重写OnActionExecuted 方法即可。
在工程中添加一个类CompressResponseAttribute.cs,
具体实现代码如下:
public class CompressResponseAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var request = actionExecutedContext.Request;
var response = actionExecutedContext.Response; var contentBytes = response.Content.ReadAsByteArrayAsync().Result;
byte[] compressedBytes;
string contentEncoding = string.Empty; using (var output = new MemoryStream())
{
if (request.Headers.AcceptEncoding.Any(v => v.Value.Equals("gzip", StringComparison.OrdinalIgnoreCase)))
{
contentEncoding = "gzip";
using (var gZipStream = new GZipStream(output, CompressionMode.Compress))
{
gZipStream.Write(contentBytes, , contentBytes.Length);
}
}
else if (request.Headers.AcceptEncoding.Any(v => v.Value.Equals("deflate", StringComparison.OrdinalIgnoreCase)))
{
contentEncoding = "deflate";
using (var deflateStream = new DeflateStream(output, CompressionMode.Compress))
{
deflateStream.Write(contentBytes, , contentBytes.Length);
}
}
compressedBytes = output.ToArray();
} if (!string.IsNullOrEmpty(contentEncoding))
{
var originalContentType = response.Content.Headers.ContentType.ToString(); response.Content = new System.Net.Http.ByteArrayContent(compressedBytes);
response.Content.Headers.Remove("Content-Type");
response.Content.Headers.Add("Content-encoding", contentEncoding);
response.Content.Headers.Add("Content-Type", originalContentType);
} base.OnActionExecuted(actionExecutedContext);
}
}
上面的代码实现的压缩方式优先为gzip。
最后,在需要压缩返回的method 上面添加 [CompressResponse] 标注 即可。
MVC 中对返回的 data 进行压缩的更多相关文章
- Asp.net MVC 中Controller返回值类型ActionResult
[Asp.net MVC中Controller返回值类型] 在mvc中所有的controller类都必须使用"Controller"后缀来命名并且对Action也有一定的要求: 必 ...
- MVC 中Controller返回值类型ActionResult
下面列举Asp.net MVC中Controller中的ActionResult返回类型 1.返回ViewResult视图结果,将视图呈现给网页 public ActionResult About() ...
- dotNET开发之MVC中Controller返回值类型ActionResult方法总结
1.返回ViewResult视图结果,将视图呈现给网页 2. 返回PartialViewResult部分视图结果,主要用于返回部分视图内容 3. 返回ContentResult用户定义的内容类型 4. ...
- 关于ASP.NET MVC 中JsonResult返回的日期值问题
最近开始用MVC做项目,在使用 JsonResult返回数据的时候,日期被反射成了/Date 1233455这种格式,遍查网上都是在客户端使用JS来处理这个问题的,这样的话,就需要在每一个涉及到日期的 ...
- 【转】在ASP.NET MVC中,使用Bundle来打包压缩js和css
在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做Bundle的东西,它用来将js和css进行压缩(多个文件可以打包成一个文件),并且可以区分调试和非调试,在调试时不进行压缩,以原 ...
- 在ASP.NET MVC中,使用Bundle来打包压缩js和css(转)
转自:http://www.cnblogs.com/xwgli/p/3296809.html 在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做Bundle的东西,它用来将js和c ...
- MVC中FileResult 返回类型返回Excel
公司中以前写的导出有问题.原来使用的XML格式字符串拼接然后转化成流输出 action public FileResult ExportJobFair() { try { string name = ...
- ASP.NET MVC中Controller返回值类型ActionResult
1.返回ViewResult视图结果,将视图呈现给网页 public class TestController : Controller { //必须存在Controller\Test\Index.c ...
- Spring MVC 中请求返回之后的页面没法加载css、js等静态文件
1.是否被拦截,这个在Web.xml配置中servlet拦截是“/”,如果是则 a.使用spring MVC 的静态资源文件 <!-- 静态文件访问,主要是针对DispatcherServlet ...
随机推荐
- 2019牛客多校第五场 B - generator 1 矩阵快速幂+十倍增+二进制倍增优化
B - generator 1 题意 给你\(x_{0}.x_{1}.a.b.b.mod\),根据\(x_{i} = a*x_{i-1} + b*x_{i-2}\)求出\(x_{n}\) 思路 一般看 ...
- Database基础(六):实现MySQL读写分离、MySQL性能调优
一.实现MySQL读写分离 目标: 本案例要求配置2台MySQL服务器+1台代理服务器,实现MySQL代理的读写分离: 用户只需要访问MySQL代理服务器,而实际的SQL查询.写入操作交给后台的2台M ...
- delphi中SendMessage使用说明
SendMessage基础知识 函数功能:该函数将指定的消息发送到一个或多个窗口.此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回.而函数PostMessage不同,将一个消息寄送到一个线 ...
- Extjs6 项目构建
一 学习前的了解: 1.Extjs6其实是结合了两个框架:Extjs 和Sencha Touch; 2.Extjs6有两个工具包: classic (存放原来Extjs的可视化组件)和 modern ...
- dubbo-monitor安装
dubbo-monitor安装 cd /opt/tools/ #包目录 tar -C /opt/ -xf dubbo-monitor-simple--assembly.tar.gz cd dubbo- ...
- vue 自定义指令(directive)实例
一.内置指令 1.v-bind:响应并更新DOM特性:例如:v-bind:href v-bind:class v-bind:title v-bind:bb 2.v-on:用于监听DOM事件: 例 ...
- 数据访问层的基类BaseDALSQL
using System; using System.Text; using System.Collections; using System.Data; using System.Data.Comm ...
- fdisk分区实例
查看磁盘分区详情 直接使用fdisk -l 或者使用fdisk /dev/sda,再使用p命令来查看 Command (m for help): p Disk /dev/sda: 32.2 GB, 3 ...
- 修改maven包本地默认位置
前言 这段时间上岸了,就有时间整理电脑的资料(强迫症重度患者),就向maven以及gradle的仓库位置动手了. 目的 改变maven的默认位置 步骤 修改maven的配置文件setting.xml( ...
- Msys2升级后不能编译
Msys2升级后不能编译 */--> code {color: #FF0000} pre.src {background-color: #002b36; color: #839496;} cod ...