zoukankan      html  css  js  c++  java
  • ASP.NET MVC 3 网站优化总结(一) 使用 Gzip 压缩

    网站开启 Gzip 压缩的好处相信很多人都已经清楚,这样做可以提高网站的性能。那么为什么很多网站没有开启 Gzip 压缩功能呢?原因有4点:防病毒软件、浏览器 bug、网站代理和服务器未配置。

    使用 IE6 时不会发送 Accept-Encoding 请求头,这样就不支持 Gzip 压缩功能了,所以这里号召大家使用 Google Chrome。在 ASP.NET MVC 3 中我们通过实现 ActionFilter 来实现,如下:

    public class CompressAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
            if (!string.IsNullOrEmpty(acceptEncoding))
            {
                acceptEncoding = acceptEncoding.ToLower();
                var response = filterContext.HttpContext.Response;
                if (acceptEncoding.Contains("gzip"))
                {
                    response.AppendHeader("Content-encoding", "gzip");
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                }
                else if (acceptEncoding.Contains("deflate"))
                {
                    response.AppendHeader("Content-encoding", "deflate");
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                }
            }
        }
    }

    这样,我们在要实现 Gzip 压缩的 Action 上添加[Compress]即可实现 Gzip 压缩,如下:

    [Compress]
    public ActionResult Index(string id)

    到这里我们就已经在 ASP.NET MVC 3 中实现了 Gzip 压缩,我们可以使用 Google Chrome 浏览器查看是否已正确实现 Gzip 压缩。使用快捷键 Ctrl+Shift+J 打开开发人员工具,查看结果如下图,发现已经实现 Gzip 压缩:

    Google Chrome Gzip 压缩查看

    本篇是 ASP.NET MVC 3 网站优化的第一篇文章,后边还有几篇文章我会陆续整理出来,希望能为 ASP.NET MVC 3 网站性能的提升起到一定的帮助作用。

  • 相关阅读:
    Asp.net(c#)导出有表格线的Excel
    精妙SQL语句收集
    SQL定时自动备份,并将备份文件加密压缩并自动下载的实现
    如何跨服务器复制表中数据
    两台Sql server的数据同步
    asp.net response.ContentType 下载文件的四种方法
    屏保显示页面控制
    开博白
    新年有感:如何能真正做好项目
    【转】OpenCV图像处理 图像的点运算 ( 灰度直方图 )
  • 原文地址:https://www.cnblogs.com/webenh/p/6206222.html
Copyright © 2011-2022 走看看