在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 进行压缩的更多相关文章

  1. Asp.net MVC 中Controller返回值类型ActionResult

    [Asp.net MVC中Controller返回值类型] 在mvc中所有的controller类都必须使用"Controller"后缀来命名并且对Action也有一定的要求: 必 ...

  2. MVC 中Controller返回值类型ActionResult

    下面列举Asp.net MVC中Controller中的ActionResult返回类型 1.返回ViewResult视图结果,将视图呈现给网页 public ActionResult About() ...

  3. dotNET开发之MVC中Controller返回值类型ActionResult方法总结

    1.返回ViewResult视图结果,将视图呈现给网页 2. 返回PartialViewResult部分视图结果,主要用于返回部分视图内容 3. 返回ContentResult用户定义的内容类型 4. ...

  4. 关于ASP.NET MVC 中JsonResult返回的日期值问题

    最近开始用MVC做项目,在使用 JsonResult返回数据的时候,日期被反射成了/Date 1233455这种格式,遍查网上都是在客户端使用JS来处理这个问题的,这样的话,就需要在每一个涉及到日期的 ...

  5. 【转】在ASP.NET MVC中,使用Bundle来打包压缩js和css

    在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做Bundle的东西,它用来将js和css进行压缩(多个文件可以打包成一个文件),并且可以区分调试和非调试,在调试时不进行压缩,以原 ...

  6. 在ASP.NET MVC中,使用Bundle来打包压缩js和css(转)

    转自:http://www.cnblogs.com/xwgli/p/3296809.html 在ASP.NET MVC4中(在WebForm中应该也有),有一个叫做Bundle的东西,它用来将js和c ...

  7. MVC中FileResult 返回类型返回Excel

    公司中以前写的导出有问题.原来使用的XML格式字符串拼接然后转化成流输出 action public FileResult ExportJobFair() { try { string name = ...

  8. ASP.NET MVC中Controller返回值类型ActionResult

    1.返回ViewResult视图结果,将视图呈现给网页 public class TestController : Controller { //必须存在Controller\Test\Index.c ...

  9. Spring MVC 中请求返回之后的页面没法加载css、js等静态文件

    1.是否被拦截,这个在Web.xml配置中servlet拦截是“/”,如果是则 a.使用spring MVC 的静态资源文件 <!-- 静态文件访问,主要是针对DispatcherServlet ...

随机推荐

  1. mysql性能查看 命中率 慢查询

    网上有很多的文章教怎么配置MySQL服务器,但考虑到服务器硬件配置的不同,具体应用的差别,那些文章的做法只能作为初步设置参考,我们需要根据自己的情况进行配置优化,好的做法是MySQL服务器稳定运行了一 ...

  2. MySQL 表的创建、修改、删除

    1.创建表 create table 表名 ( 列名 类型 是否可以为空 列名 类型 是否可以为空 ) engine=innodb default charset=utf8; 是否可以为控制.null ...

  3. 将日志(Microsoft.Extensions.Logging)添加到.NET Core控制台应用程序

    在.NET Core项目中,日志记录是通过依赖项注入进行管理的. 尽管这对于ASP.NET项目效果很好,但在启动Startup.cs中的新项目时,所有这些都会自动创建,而在控制台应用程序中则需要一些配 ...

  4. python3_列表(修改,添加和删除元素操作)

    前言:列表的定义:列表是由一系列按特定顺序排列的元素组成.即列表是一个有序集合. 1.修改列表元素 由前言知列表是一个有序集合,因此在修改列表元素时我们需指定列表名和要修改的元素的索引,再指定该元素的 ...

  5. python学习笔记:数据类型——列表/数组(list)

    Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素.通过下标访问列表中的元素(又称索引.角标),下标从0开始计数.list定义,使用中括号[]. l ...

  6. CS如何调用JS

    this.ClientScript.RegisterStartupScript(this.GetType(), "", "RunClick()", true); ...

  7. jumpserver注意事项以及报错处理

    需要注意下面亮点 在使用jumpserver过程中,有一步是系统用户推送,要推送成功,client(后端服务器)要满足以下条件: 后端服务器需要有python.sudo环境才能使用推送用户,批量命令等 ...

  8. mac 完全卸载vscode

    原文分隔线====================== while writing go this morning, I found that the wrong code are not under ...

  9. Javafx弹窗

    在javafx中可能用到一些弹窗,比如点击某个按钮后弹出弹窗提示信息等等 Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle( ...

  10. spring基于注解的事务控制

    pom配置: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http ...