ASP.NET 首页性能的十大做法

前言

本文是我对ASP.NET页面载入速度提高的一些做法,这些做法分为以下部分:

针对上述做法,我们首先需要一个 HTTP 模块,它是整个页面流程的入口和核心。

一、自定义Response.Filter得到输出流stream生成动态页面的静态内容(磁盘缓存)

如下的代码我们可以看出,我们以 request.RawUrl 为缓存基础,因为它可以包含任意的QueryString变量,然后我们用MD5加密RawUrl 得到服务器本地文件名的变量,再实例化一个FileInfo操作该文件,如果文件最后一次生成时间小于7天,我们就使用.Net2.0新增的TransmitFile方法将存储文件的静态内容发送到浏览器。如果文件不存在,我们就操作 response.Filter 得到的 Stream 传递给 CommonFilter 类,并利用FileStream写入动态页面的内容到静态文件中。

namespace  ASPNET_CL.Code.HttpModules {
     public  class  CommonModule : IHttpModule {
         public  void  Init( HttpApplication application ) {
            application.BeginRequest += Application_BeginRequest;
        }

         private  void  Application_BeginRequest(  object  sender, EventArgs e ) {
            var context = HttpContext.Current;
            var request = context.Request;
            var url = request.RawUrl;

            var response = context.Response;
            var path = GetPath( url );
            var file =  new  FileInfo( path );

             if  ( DateTime.Now.Subtract( file.LastWriteTime ).TotalDays < 7 ) {
                response.TransmitFile( path );
                response.End();
                 return;
            }
             try  {
                var stream = file.OpenWrite();
                response.Filter =  new  CommonFilter( response.Filter, stream );
            }
             catch  ( Exception ) {
                 //Log.Insert("");
            }
        }

         public  void  Dispose() {

        }

         private  static  string  GetPath(  string  url ) {
            var hash = Hash( url );
             string  fold = HttpContext.Current.Server.MapPath(  "~/Temp/"  );
             return  string.Concat( fold, hash );
        }

         private  static  string  Hash(  string  url ) {
            url = url.ToUpperInvariant();
            var md5 =  new  System.Security.Cryptography.MD5CryptoServiceProvider();
            var bs = md5.ComputeHash( Encoding.ASCII.GetBytes( url ) );
            var s =  new  StringBuilder();
             foreach  ( var b  in  bs ) {
                s.Append( b.ToString(  "x2"  ).ToLower() );
            }
             return  s.ToString();
        }
    }
}

二、页面GZIP压缩

对页面GZIP压缩几乎是每篇讲解高性能WEB程序的几大做法之一,因为使用GZIP压缩可以降低服务器发送的字节数,能让客户感觉到网页的速度更快也减少了对带宽的使用情况。当然,这里也存在客户端的浏览器是否支持它。因此,我们要做的是,如果客户端支持GZIP,我们就发送GZIP压缩过的内容,如果不支持,我们直接发送静态文件的内容。幸运的是,现代浏览器IE6.7.8.0,火狐等都支持GZIP。

为了实现这个功能,我们需要改写上面的 Application_BeginRequest 事件:

         private void Application_BeginRequest( object sender, EventArgs e ) {
            var context = HttpContext.Current;
            var request = context.Request;
            var url = request.RawUrl;

            var response = context.Response;
            var path = GetPath( url );
            var file = new FileInfo( path );

            // 使用页面压缩
              ResponseCompressionType compressionType = this.GetCompressionMode( request );
            if ( compressionType != ResponseCompressionType.None ) {
                response.AppendHeader( "Content-Encoding", compressionType.ToString().ToLower() );
                if ( compressionType == ResponseCompressionType.GZip ) {
                    response.Filter = new GZipStream( response.Filter, CompressionMode.Compress );
                }
                else {
                    response.Filter = new DeflateStream( response.Filter, CompressionMode.Compress );
                }
            }

            if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) {
                response.TransmitFile( path );
                response.End();
                return;
            }
            try {
                var stream = file.OpenWrite();
                response.Filter = new CommonFilter( response.Filter, stream );
            }
            catch ( Exception ) {
                //Log.Insert("");
            }
        }

        private ResponseCompressionType GetCompressionMode( HttpRequest request ) {
            string acceptEncoding = request.Headers[ "Accept-Encoding" ];
            if ( string.IsNullOrEmpty( acceptEncoding ) )
                return ResponseCompressionType.None;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            if ( acceptEncoding.Contains( "GZIP" ) )
                return ResponseCompressionType.GZip;
            else if ( acceptEncoding.Contains( "DEFLATE" ) )
                return ResponseCompressionType.Deflate;
            else
                return ResponseCompressionType.None;
        }

        private enum ResponseCompressionType {
            None,
            GZip,
            Deflate
        }

三、OutputCache 编程方式输出页面缓存

ASP.NET内置的 OutputCache 缓存可以将内容缓存在三个地方:Web服务器、代理服务器和浏览器。当用户访问一个被设置为 OutputCache的页面时,ASP.NET在MSIL之后,先将结果写入output cache缓存,然后在发送到浏览器,当用户访问同一路径的页面时,ASP.NET将直接发送被Cache的内容,而不经过.aspx编译以及执行MSIL的过程,所以,虽然程序的本身效率没有提升,但是页面载入速度却得到了提升。

为了实现这个功能,我们继续改写上面的 Application_BeginRequest 事件,我们在 TransmitFile 后,将这个路径的页面以OutputCache编程的方式缓存起来:

 private void Application_BeginRequest( object sender, EventArgs e ) {
         
           //.............

            if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalMinutes < 5 ) {
                response.TransmitFile( path );
                // 添加 OutputCache 缓存头,并缓存在客户端
                  response.Cache.SetExpires( DateTime.Now.AddMinutes( 5 ) );
                response.Cache.SetCacheability( HttpCacheability.Public );
                response.End();
                return;
            }
           
           //............
 }

原文转自博客园:http://www.cnblogs.com/cnshangsha/

更多...

作者:BuildNewApp
出处:http://syxchina.cnblogs.comBuildNewApp.com
本文版权归作者、博客园和百度空间共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则作者会诅咒你的。
如果您阅读了我的文章并觉得有价值请点击此处,谢谢您的肯定1。
原文地址:https://www.cnblogs.com/syxchina/p/2197336.html