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.全局注册

  • 相关阅读:
    解读MSP430F169的头文件们
    解决编辑安装falkon中碰到缺少ecm问题
    vim基础普及
    本科2020专业目录
    cp 文件复制命令
    mkdir rmdir
    whereis ,which 文件查找
    gitlab软件的安装与使用
    如何节省数据库的成本
    innodb_undo_tablespaces参数引发的启动报错
  • 原文地址:https://www.cnblogs.com/HTLucky/p/12856279.html
Copyright © 2011-2022 走看看