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 ...
随机推荐
- linux基础知识-常用命令
ifconfig :查看当前ip hostname:查看主机名 vim /etc/hosts:修改地址映射 service iptables status : 查看防火墙状态 chkconfig ip ...
- Redis缓存接入监控、运维平台CacheCloud
改造RedisConnectionFactory /** * 根据缓存策略的不同,RedisConnectionFactory不同 * 示例是单机模式. * * @return */@Beanpubl ...
- 嵌入式C语言4.3 C语言内存空间的使用-指针与运算符
1. ++.--.+.- int a=100; a+1; 对比: int *p=xxx; [0x12] p+1; [0x12+1*sizeof(*p)] 指针的加法(减法)运算, ...
- CPython,PyPy?Python和这两个东西有什么关系
https://blog.csdn.net/fu6543210/article/details/90770794 python是一种编程语言.但这种语言有多种实现,而且与其他语言不同,python并没 ...
- git 上传你代码到码云
转载自:http://blog.csdn.net/u013776188/article/details/60867437
- windows配置环境变量
windows配置环境变量 1.第一步 2.第二步 3.第三步
- springboot中的mybatis是如果使用pagehelper的
springboot中使用其他组件都是基于自动配置的AutoConfiguration配置累的,pagehelper插件也是一样的,通过PageHelperAutoConfiguration的,这个类 ...
- go 区分指针
先看一段代码 先放一段代码,人工运行一下,看看自己能做对几题? package main import "fmt" func main() { var a int = 1 var ...
- C语言各种进制输出
#include<stdio.h> int main() { ; float f = 12.0; printf("十进制输出:%d\n", number); print ...
- Invoke-Obfuscation混淆ps文件绕过Windows_Defender
前提 powershell只能针对win7之后的系统,之前的win操作系统默认没有安装powershell. 所在目录:C:\Windows\System32\WindowsPowerShell\v1 ...