如何提高ASP.NET页面载入速度的方法

来源:互联网 发布:mac终端连接linux中断 编辑:程序博客网 时间:2024/04/28 17:13

1.采用 HTTP Module 控制页面的生命周期。

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

3.页面GZIP压缩。

4.OutputCache 编程方式输出页面缓存。

5.删除页面空白字符串。(类似Google)

6.完全删除ViewState。

7.删除服务器控件生成的垃圾NamingContainer。

8.使用计划任务按时生成页面。(本文不包含该做法的实现)

9.JS,CSS压缩、合并、缓存,图片缓存。(限于文章篇幅,本文不包含该做法的实现)

10.缓存破坏。(不包含第9做法的实现)

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

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

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

view source
< id="highlighter_476669_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01namespace ASPNET_CL.Code.HttpModules
02{
03    public class CommonModule : IHttpModule
04    {
05        public void Init(HttpApplication application)
06        {
07            application.BeginRequest += Application_BeginRequest;
08        }
09        private void Application_BeginRequest(object sender, EventArgs e)
10        {
11            var context= HttpContext.Current; 
12            var request = context.Request; 
13            var url = request.RawUrl;
14            var response = context.Response; 
15            var path = GetPath(url); 
16            var file = new FileInfo(path); 
17            if (DateTime.Now.Subtract(file.LastWriteTime).TotalDays < 7)
18            {
19                response.TransmitFile(path); 
20                response.End();
21                return;
22            
23            try
24            {
25                var stream = file.OpenWrite();
26                response.Filter= new CommonFilter(response.Filter, stream);
27            }
28            catch (Exception)
29            {
30                Log.Insert("");
31            }
32        
33        public void Dispose() { }
34        private static string GetPath(string url)
35        {
36            var hash = Hash(url); 
37            string fold = HttpContext.Current.Server.MapPath("~/Temp/"); 
38            return string.Concat(fold, hash);
39        }
40        private static string Hash(string url)
41        {
42            url = url.ToUpperInvariant(); 
43            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
44            var bs = md5.ComputeHash(Encoding.ASCII.GetBytes(url)); 
45            var s = new StringBuilder();
46            foreach (var b in bs)
47            {
48                s.Append(b.ToString("x2").ToLower());
49            }
50            return s.ToString();
51        }
52    }
53}

二、页面GZIP压缩

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

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

view source
< id="highlighter_76620_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01private void Application_BeginRequest(object sender, EventArgs e)
02{
03    var context = HttpContext.Current;
04    var request = context.Request;
05    var url = request.RawUrl;
06    var response = context.Response;
07    var path = GetPath(url);
08    var file = new FileInfo(path);
09    // 使用页面压缩 ResponseCompressionType compressionType = this.GetCompressionMode(request ); 
10    if (compressionType != ResponseCompressionType.None)
11    {
12        response.AppendHeader("Content-Encoding", compressionType.ToString().ToLower());
13        if (compressionType == ResponseCompressionType.GZip)
14        {
15            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
16        }
17        else
18        {
19            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
20        }
21    }
22    if (DateTime.Now.Subtract(file.LastWriteTime).TotalMinutes < 5)
23    {
24        response.TransmitFile(path);
25        response.End();
26        return;
27    }
28    try
29    {
30        var stream = file.OpenWrite();
31        response.Filter = new CommonFilter(response.Filter, stream);
32    }
33    catch (Exception)
34    {
35        //Log.Insert(""); 
36    }
37}
38private ResponseCompressionType GetCompressionMode(HttpRequest request)
39{
40    string acceptEncoding = request.Headers["Accept-Encoding"];
41    if (string.IsNullOrEmpty(acceptEncoding))
42        return ResponseCompressionType.None;
43    acceptEncoding = acceptEncoding.ToUpperInvariant();
44    if (acceptEncoding.Contains("GZIP"))
45        return ResponseCompressionType.GZip;
46    else if (acceptEncoding.Contains("DEFLATE"))
47        return ResponseCompressionType.Deflate;
48    else
49        return ResponseCompressionType.None;
50}
51private 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编程的方式缓存起来:

view source
< id="highlighter_422186_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01private void Application_BeginRequest(object sender, EventArgs e)
02{ //.............
03    if (DateTime.Now.Subtract(file.LastWriteTime).TotalMinutes < 5)
04    {
05        response.TransmitFile(
06            path);
07        // 添加 OutputCache 缓存头,并缓存在客户端 
08        response.Cache.SetExpires(DateTime.Now.AddMinutes(
09    5));
10        response.Cache.SetCacheability(HttpCacheability.Public);
11        response.End();
12        return;
13    }
14    //............ 
15}

四、实现CommonFilter类过滤ViewState、过滤NamingContainer、空白字符串,以及生成磁盘的缓存文件

我们传入response.Filter的Stream对象给CommonFilter类:

首先,我们用先Stream的Write方法实现生成磁盘的缓存文件,代码如下,在这些代码中,只有初始化构造函数,Write方法,Close方式是有用的,其中FileStream字段是生成静态文件的操作对象:

view source
< id="highlighter_485625_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01namespace ASPNET_CL.Code.HttpModules
02{
03    public class CommonFilter : Stream
04    {
05        private readonly Stream _responseStream;
06        private readonly FileStream _cacheStream;
07        public override bool CanRead
08        {
09            get
10            {
11                return false;
12            }
13        }
14        public override bool CanSeek
15        {
16            get
17            {
18                return false;
19            }
20        }
21        public override bool CanWrite
22        {
23            get
24            {
25                return _responseStream.CanWrite;
26            }
27        }
28        public override long Length
29        {
30            get
31            {
32                throw new NotSupportedException();
33            }
34        }
35        public override long Position
36        {
37            get
38            {
39                throw new NotSupportedException();
40            }
41            set
42            {
43                throw
44                    new NotSupportedException();
45            }
46        }
47        public CommonFilter(Stream responseStream, FileStream stream)
48        {
49            _responseStream = responseStream;
50            _cacheStream = stream;
51        }
52        public override long Seek(long offset, SeekOrigin origin)
53        {
54            throw new NotSupportedException();
55        }
56        public override void SetLength(long length)
57        {
58            throw new NotSupportedException();
59        }
60        public override int Read(byte[] buffer, int offset, int count)
61        {
62            throw new NotSupportedException();
63        }
64        public override void Flush()
65        {
66            _responseStream.Flush();
67            _cacheStream.Flush();
68        }
69        public override void Write(byte[] buffer, int offset, int count)
70        {
71            _cacheStream.Write(
72                buffer, offset, count);
73            _responseStream.Write(buffer, offset, count);
74        }
75        public override void Close()
76        {
77            _responseStream.Close();
78            _cacheStream.Close();
79        }
80        protected override void Dispose(bool disposing)
81        {
82            if (disposing)
83            {
84                _responseStream.Dispose();
85                _cacheStream.Dispose();
86            }
87        }
88    }
89}

然后我们利用正则完全删除ViewState:

view source
< id="highlighter_554322_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01// 过滤ViewState 
02private string ViewStateFilter(string strHTML)
03{
04    string matchString1 = "type=/"hidden/" name=/"__VIEWSTATE/" id=/"__VIEWSTATE/"";
05    string matchString2 = "type=/"hidden/" name=/"__EVENTVALIDATION/" id=/"__EVENTVALIDATION/"";
06    stringmatchString3 = "type=/"hidden/" name=/"__EVENTTARGET/" id=/"__EVENTTARGET/"";
07    stringmatchString4 = "type=/"hidden/" name=/"__EVENTARGUMENT/" id=/"__EVENTARGUMENT/"";
08    string positiveLookahead1 = "(?=.*(" + Regex.Escape(matchString1) + "))";
09    stringpositiveLookahead2 = "(?=.*(" + Regex.Escape(matchString2) + "))";
10    string positiveLookahead3 = "(?=.*(" + Regex.Escape(matchString3) + "))";
11    string positiveLookahead4 = "(?=.*(" + Regex.Escape(matchString4) + "))";
12    RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;
13    Regex[] arrRe = new Regex[] { new Regex("//s*<div>" + positiveLookahead1 + "(.*?)</div>//s*", opt), new Regex("//s*<div>" + positiveLookahead2 + "(.*?)</div>//s*", opt), new Regex("//s*<div>" + positiveLookahead3 + "(.*?)</div>//s*", opt), new Regex("//s*<div>" + positiveLookahead3 + "(.*?)</div>//s*", opt), new Regex("//s*<div>" + positiveLookahead4 + "(.*?)</div>//s*", opt) };
14    foreach (Regex re in arrRe)
15    {
16        strHTML = re.Replace(strHTML, "");
17    
18    return strHTML;
19}

以下是删除页面空白的方法:

view source
< id="highlighter_907629_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01// 删除空白 
02private Regex tabsRe = new Regex("//t", RegexOptions.Compiled | RegexOptions.Multiline);
03private Regex carriageReturnRe = new Regex(">//r//n<", RegexOptions.Compiled | RegexOptions.Multiline);
04private Regex carriageReturnSafeRe = new Regex("//r//n", RegexOptions.Compiled | RegexOptions.Multiline);
05private Regex multipleSpaces = new Regex(" ", RegexOptions.Compiled | RegexOptions.Multiline);
06private Regex spaceBetweenTags = new Regex(">//s<", RegexOptions.Compiled | RegexOptions.Multiline);
07private string WhitespaceFilter(string html)
08{
09    html = tabsRe.Replace(html, string.Empty);
10    html = carriageReturnRe.Replace(html, "><");
11    html = carriageReturnSafeRe.Replace(html, " ");
12    while (multipleSpaces.IsMatch(html))
13        html = multipleSpaces.Replace(html, " ");
14    html = spaceBetweenTags.Replace(html, "><");
15    html = html.Replace("//<![CDATA[", "");
16    html = html.Replace("//]]>", "");
17    return html;
18}

以下是删除ASP.NET控件的垃圾UniqueID名称方法:

view source
< id="highlighter_121839_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
1        // 过滤NamingContainer <BR>        private string NamingContainerFilter(string html)<BR>        {<BR>            RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;<BR>            Regex re = new Regex("( name=/")(?=.*(" + Regex.Escape("$") + "))([^/"]+?)(/")", opt);<BR>            html = re.Replace(html, new MatchEvaluator(delegate(Match m)<BR>            {<BR>                int lastDollarSignIndex = m.Value.LastIndexOf('$');<BR>                if (lastDollarSignIndex >= 0)<BR>                {<BR>                    return m.Groups[1].Value + m.Value.Substring(lastDollarSignIndex + 1);<BR>                }<BR>                else<BR>                {<BR>                    return m.Value;<BR>                }<BR>            }));<BR>            return html;

最后,我们把以上过滤方法整合到CommonFilter类的Write方法:

view source
< id="highlighter_107066_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
01public override void Write(byte[] buffer, int offset, int count)
02{
03    // 转换buffer为字符串
04    byte[] data = new byte[count];
05    Buffer.BlockCopy(buffer, offset, data, 0, count);
06    string html = System.Text.Encoding.UTF8.GetString(buffer);
07    // 以下整合过滤方法 
08    html = NamingContainerFilter(html);
09    html = ViewStateFilter(html);
10    html = WhitespaceFilter(html);
11    byte[] outdata = System.Text.Encoding.UTF8.GetBytes(html);
12    // 写入磁盘 
13    _cacheStream.Write(outdata, 0, outdata.GetLength(0));
14    _responseStream.Write(outdata, 0, outdata.GetLength(0));
15}

五、缓存破坏

经过以上程序的实现,网页已经被高速缓存在客户端了,如果果用户访问网站被缓存过的页面,则页面会以0请求的速度加载页面。但是,如果后台更新了某些数据,前台用户则不能及时看到最新的数据,因此要改变这种情况,我们必须破坏缓存。根据我们如上的程序,我们破坏缓存只需要做2步:更新服务器上的临时文件,删除OutputCache过的页面。

更新服务器上的文件我们只需删除这个文件即可,当某一用户第一次访问该页面时会自动生成,当然,你也可以用程序先删除后生成:

view source
< id="highlighter_394560_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
1   // 更新文件 
2foreach (var file in Directory.GetFiles(HttpRuntime.AppDomainAppPath + "Temp"))
3   {
4       File.Delete(file);
5   }

要删除OutputCache关联的缓存项,代码如下,我们只需要保证该方法的参数,指页面的绝对路径是正确的,路径不能使用../这样的相对路径:

view source
< id="highlighter_560200_clipboard" title="copy to clipboard" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="16" height="16" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" type="application/x-shockwave-flash">
print?
1// 删除缓存  
2HttpResponse.RemoveOutputCacheItem( "/Default.aspx" );

到此,我们实现了针对一个页面的性能,重点是载入速度的提高的一些做法,希望对大家有用~!

原创粉丝点击