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 ...
随机推荐
- AcWing 225. 矩阵幂求和 (矩阵快速幂+分治)打卡
题目:https://www.acwing.com/problem/content/227/ 题意:给你n,k,m,然后输入一个n阶矩阵A,让你求 S=A+A^2+A^3.+......+A^k 思 ...
- sync.Once.Do(f func())
sync.Once.Do(f func())是一个挺有趣的东西,能保证once只执行一次,无论你是否更换once.Do(xx)这里的方法,这个sync.Once块只会执行一次. package mai ...
- C++ placement new与内存池
参考:https://blog.csdn.net/Kiritow/article/details/51314612 有些时候我们需要能够长时间运行的程序(例如监听程序,服务器程序)对于这些7*24运行 ...
- Windows-右键菜单添加选项
新建 add.reg 输入选项名和选项对应程序路径 Windows Registry Editor Version 5.00 [HKEY_CLASSES_ROOT\*\shell\选项名] [HKEY ...
- sqlserver 找不到驱动,显示项目缺少class办法
maven使用 <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId> ...
- winform DataGridView的虚模式填充,CellValueNeeded事件的触发条件
虚模式填充常用来处理大量数据,某个字段的显示问题. DataGridView是.net 2.0新增的表格数据编辑和显示控件,简单的数据显示和编辑,只需直接和数据源绑定就可以了. 对于 一些特殊情况,我 ...
- WinDows应急响应基础
文件排查 开机启动有无异常文件 msconfig 敏感的文件路径 %WINDIR% %WINDIR%\SYSTEM32\ %TEMP% %LOCALAPPDATA% %APPDATA% 用户目录 新建 ...
- os.walk|图片数据集
该函数的功能:遍历指定文件夹下的所有[路径][文件夹][文件名] ''' os.walk(top[, topdown=True[, onerror=None[, followlinks=False]] ...
- js node.children与node.childNodes与node.firstChild,node,lastChild之间的关系
博客搬迁,给你带来的不便,敬请谅解! http://www.suanliutudousi.com/2017/11/06/js-node-children%e4%b8%8enode-childnodes ...
- Python之小测试:用正则表达式写一个小爬虫用于保存贴吧里的所有图片
很简单的两步: 1.获取网页源代码 2.利用正则表达式提取出图片地址 3.下载 #!/usr/bin/python #coding=utf8 import re # 正则表达式 import urll ...