zoukankan      html  css  js  c++  java
  • .NET MVC实现压缩

    压缩也是一种优化的方式,能帮助我们缩减传输的数据量。网站开发中包含着多种压缩格式,最主要的还是看浏览器支不支持。通常的做法是判断请求头中包含什么格式的压缩,服务端在根据相应的压缩格式返回相应的数据。接下来通过重写.net mvc中的ActionFilterAttribute来实现服务端的压缩

    一.压缩实现

       public class CompressAttribute: ActionFilterAttribute
        {
            public override void OnActionExecuted(ActionExecutedContext filterContext)
            {
                var encoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];   //获取请求头中的压缩格式
                if (!string.IsNullOrWhiteSpace(encoding))
                {
                    encoding = encoding.ToLower();
                    var response = filterContext.HttpContext.Response;
                    if (encoding.Contains("gzip"))  //判断压缩格式返回相应的压缩
                    {
                        response.AppendHeader("Content-encoding", "gzip");
                        response.Filter = new GZipStream(response.Filter,CompressionMode.Compress);
                    }
                    else if (encoding.Contains("deflate"))
                    {
                        response.AppendHeader("Content-encoding", "deflate");
                        response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    }
                }
            }
        }

    二.注册扩展的压缩特性 

      1.在Action上注册

      2.在Controller上注册

      3.全局注册

  • 相关阅读:
    GO开发[一]:golang语言初探
    Python带参数的装饰器
    Python函数篇
    19. logging模块
    18. json模块
    17. os模块
    16. sys模块
    15. random模块
    14. 模块-time模块
    29. java面向对象项目
  • 原文地址:https://www.cnblogs.com/HTLucky/p/12856279.html
Copyright © 2011-2022 走看看