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 ...
随机推荐
- delphi 随意将函数执行权限提高到Ring0源代码
//随意将函数执行权限提高到Ring0源代码//Windows 2K以上的操作系统,//用途: 提供超级简单使用的APIrocessRing0(),//可将delphi中的任意函数由原來的Ring3权 ...
- AcWing 243. 一个简单的整数问题2 (树状数组)打卡
题目:https://www.acwing.com/problem/content/244/ 题意:区间加,区间查询 思路:我们把原先那个差分数组分解一下 ∑i=1x∑j=1ib[j]=∑i=1x(x ...
- HTML5: 目录
ylbtech-HTML5: 目录 1.返回顶部 1. http://www.runoob.com/html/html5-intro.html 2. http://www.w3school.com.c ...
- 数据分析系列篇:玩转excel
数据分析系列篇:玩转excel 不知道现在怎么也变得这么鸡婆,连excel都要准备写一篇.没办法,还有很多不是做数据的小伙伴们不会excel啊,抱着不抛弃.不放弃的态度,就讲下excel如何玩转.其实 ...
- Linux打开关闭ping
#关闭 ” >/proc/sys/net/ipv4/icmp_echo_ignore_all #打开 ” >/proc/sys/net/ipv4/icmp_echo_ignore_all
- 201⑨湘潭邀请赛 Chika and Friendly Pairs(HDU6534)
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=6534 题意: 给你一个数组,对于第i个数来说,如果存在一个位置j,使得j>i并且a[j]-k&l ...
- Leetcode 跳跃游戏 II
题目链接:https://leetcode-cn.com/problems/jump-game-ii/ 题目大意: 略. 分析: 贪心 + DP. 代码如下: class Solution { pub ...
- jpql简单l查询
JPQL全称Java Persistence Query Language package com.ytkj.entity; import javax.persistence.*; import ja ...
- 基于MFC的Media Player播放器的制作(4---功能实现代码)
| 版权声明:本文为博主原创文章,未经博主允许不得转载. PandaPlayerDlg.h // PandaPlayerDlg.h : header file // //{{AFX_INCLUDE ...
- 微信公众号开发笔记-验证token
开发 话不多说我们直接进入主题 我们先去微信公众号申请一个公众号: 申请完成之后我们找到开发下的基本配置 然后找到进行基本配置,我们需要一个url地址来验证,这里的地址必需要是外网,Token是我们任 ...