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

前言

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

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写入动态页面的内容到静态文件中。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

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 事件:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

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编程的方式缓存起来:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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;

    }

    //............

}

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

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

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

namespace ASPNET_CL.Code.HttpModules

{

    public class CommonFilter : Stream

    {

        private readonly Stream _responseStream;

        private readonly FileStream _cacheStream;

        public override bool CanRead

        {

            get

            {

                return false;

            }

        }

        public override bool CanSeek

        {

            get

            {

                return false;

            }

        }

        public override bool CanWrite

        {

            get

            {

                return _responseStream.CanWrite;

            }

        }

        public override long Length

        {

            get

            {

                throw new NotSupportedException();

            }

        }

        public override long Position

        {

            get

            {

                throw new NotSupportedException();

            }

            set

            {

                throw

                    new NotSupportedException();

            }

        }

        public CommonFilter(Stream responseStream, FileStream stream)

        {

            _responseStream = responseStream;

            _cacheStream = stream;

        }

        public override long Seek(long offset, SeekOrigin origin)

        {

            throw new NotSupportedException();

        }

        public override void SetLength(long length)

        {

            throw new NotSupportedException();

        }

        public override int Read(byte[] buffer, int offset, int count)

        {

            throw new NotSupportedException();

        }

        public override void Flush()

        {

            _responseStream.Flush();

            _cacheStream.Flush();

        }

        public override void Write(byte[] buffer, int offset, int count)

        {

            _cacheStream.Write(

                buffer, offset, count);

            _responseStream.Write(buffer, offset, count);

        }

        public override void Close()

        {

            _responseStream.Close();

            _cacheStream.Close();

        }

        protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                _responseStream.Dispose();

                _cacheStream.Dispose();

            }

        }

    }

}

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// 过滤ViewState

private string ViewStateFilter(string strHTML)

{

    string matchString1 = "type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\"";

    string matchString2 = "type=\"hidden\" name=\"__EVENTVALIDATION\" id=\"__EVENTVALIDATION\"";

    stringmatchString3 = "type=\"hidden\" name=\"__EVENTTARGET\" id=\"__EVENTTARGET\"";

    stringmatchString4 = "type=\"hidden\" name=\"__EVENTARGUMENT\" id=\"__EVENTARGUMENT\"";

    string positiveLookahead1 = "(?=.*(" + Regex.Escape(matchString1) + "))";

    stringpositiveLookahead2 = "(?=.*(" + Regex.Escape(matchString2) + "))";

    string positiveLookahead3 = "(?=.*(" + Regex.Escape(matchString3) + "))";

    string positiveLookahead4 = "(?=.*(" + Regex.Escape(matchString4) + "))";

    RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;

    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) };

    foreach (Regex re in arrRe)

    {

        strHTML = re.Replace(strHTML, "");

    }

    return strHTML;

}

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// 删除空白

private Regex tabsRe = new Regex("\\t", RegexOptions.Compiled | RegexOptions.Multiline);

private Regex carriageReturnRe = new Regex(">\\r\\n<", RegexOptions.Compiled | RegexOptions.Multiline);

private Regex carriageReturnSafeRe = new Regex("\\r\\n", RegexOptions.Compiled | RegexOptions.Multiline);

private Regex multipleSpaces = new Regex(" ", RegexOptions.Compiled | RegexOptions.Multiline);

private Regex spaceBetweenTags = new Regex(">\\s<", RegexOptions.Compiled | RegexOptions.Multiline);

private string WhitespaceFilter(string html)

{

    html = tabsRe.Replace(html, string.Empty);

    html = carriageReturnRe.Replace(html, "><");

    html = carriageReturnSafeRe.Replace(html, " ");

    while (multipleSpaces.IsMatch(html))

        html = multipleSpaces.Replace(html, " ");

    html = spaceBetweenTags.Replace(html, "><");

    html = html.Replace("//<![CDATA[", "");

    html = html.Replace("//]]>", "");

    return html;

}

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

// 过滤NamingContainer

private string NamingContainerFilter(string html)

{

    RegexOptions opt = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.Compiled;

    Regex re = new Regex("( name=\")(?=.*(" + Regex.Escape("$") + "))([^\"]+?)(\")", opt);

    html = re.Replace(html, new MatchEvaluator(delegate(Match m)

    {

        int lastDollarSignIndex = m.Value.LastIndexOf(‘$‘);

        if (lastDollarSignIndex >= 0)

        {

            return m.Groups[1].Value + m.Value.Substring(lastDollarSignIndex + 1);

        }

        else

        {

            return m.Value;

        }

    }));

    return html;

}

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


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

public override void Write(byte[] buffer, int offset, int count)

{

    // 转换buffer为字符串

    byte[] data = new byte[count];

    Buffer.BlockCopy(buffer, offset, data, 0, count);

    string html = System.Text.Encoding.UTF8.GetString(buffer);

    // 以下整合过滤方法

    html = NamingContainerFilter(html);

    html = ViewStateFilter(html);

    html = WhitespaceFilter(html);

    byte[] outdata = System.Text.Encoding.UTF8.GetBytes(html);

    // 写入磁盘

    _cacheStream.Write(outdata, 0, outdata.GetLength(0));

    _responseStream.Write(outdata, 0, outdata.GetLength(0));

}

五、缓存破坏

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

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


1

2

3

4

5

   // 更新文件

foreach (var file in Directory.GetFiles(HttpRuntime.AppDomainAppPath + "Temp"))

   {

       File.Delete(file);

   }

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


1

2

// 删除缓存 

HttpResponse.RemoveOutputCacheItem( "/Default.aspx" );

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

转自51cto.com,原文标题:ASP.NET 首页性能的十大做法

本文地址:http://www.cnblogs.com/atree/archive/2010/05/16/ASP-NET-Page-HTTP-Module-OutputCache-CommonFilter.html

时间: 2024-08-04 20:49:51

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

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

前言 本文是我对ASP.NET页面载入速度提高的一些做法,这些做法分为以下部分: 目录 1.采用 HTTP Module 控制页面的生命周期. 2.自定义Response.Filter得到输出流stream生成动态页面的静态内容(磁盘缓存). 3.页面GZIP压缩. 4.OutputCache 编程方式输出页面缓存. 5.删除页面空白字符串.(类似Google) 6.完全删除ViewState. 7.删除服务器控件生成的垃圾NamingContainer. 8.使用计划任务按时生成页面.(本文不

ASP.NET页面优化性能提升方法记录

今天与大家分享:一种优化页面执行速度的方法.采用这个方法,可以使用页面的执行速度获得[8倍]的提升效果. 为了让您对优化的效果有个直观的了解,我准备了下面的测试结果截图: 测试环境:1. Windows Server 2003 SP22. Viaual Studio 2008,使用自带的WebDev.WebServer.EXE运行网站程序.3. (ThinkPad SL510):Core2 T6670 2.2GHz, 4G内存 二个红框中的数字反映了优化前后的执行时间.数字表明:优化前后,执行时

ASP.NET页面刷新的实现方法总结

先看看ASP.NET页面刷新的实现方法: 第一: C#代码   private void Button1_Click( object sender, System.EventArgs e ) { Response.Redirect( Request.Url.ToString( ) ); } 第二: C#代码   private void Button2_Click( object sender, System.EventArgs e ) { Response.Write( " < scri

asp.net页面跳转的方法

1.超链接 2.response.Redirect(“UrlString”) 过程: 浏览器操作--服务器编译--发回页面--浏览器按新URl发出请求--服务器响应新URl请求--编译新页面--发回浏览器 3.Server.Transfer(“UrlString”) 4.PostBackUrl 凡是具有IButtonControl借口的控件都有PostBackUrl属性,用来定义提交至那个页面地址.(可以是本站也可以使外站) 这种方法的跳转,目标页面可以调用原页面中控件的值. asp.net页面

在WCF数据访问中使用缓存提高Winform字段中文显示速度的方法

本文较为详细的讲述了在WCF数据访问中使用缓存提高Winform字段中文显示速度的方法,分享给大家供大家参考之用.具体方法如下: 在我们开发基于WCF访问方式的Winform程序的时候,一般情况下需要对界面显示的字段进行中文显示的解析.如果是硬编码进行中文显示,那么除了不方便调整及代码臃肿外,性能上没有什么问题,但是不建议这样处理:一般情况下,我们把中文对照信息放到业务类里面去统一解析,但是这样会导致每次WCF访问方式请求解析中文化的操作耗费一定的响应时间.如果使用缓存存储中文字段的对照表,那么

jsp的凝视可能会影响页面载入速度

在jsp页面使用"<!-- -->"的凝视,凝视里面的java代码还是会得到运行,能够再查看页面源码上看到运行完毕的内容,这样就会让不希望运行的代码得到运行.影响载入速度.比方例如以下代码: 性别:<select name="qureyItemGroup.sex" class="selinp" style="width:75px;"> <option value="">所

asp.net 页面跳转的方法

目前知道有4种: 1超链接 2.response.redirect("urlString") 3.server.transfer("urlString") 4.postbackurl 超链接: 首先是添加一个新的web窗体,然后在原有的默认页中添加一个超链接. <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default2.aspx&q

ASP.NET 页面之间传递参数方法

1.通过URL链接地址传递 (1) send.aspx代码 protected void Button1_Click(object sender, EventArgs e) { Request.Redirect("Default2.aspx?username=honge"); } (2) receive.aspx代码 string username = Request.QueryString["username"];//这样可以得到参数值. 2.POST方式传递 (

提高 SharePoint 页面访问速度之&ldquo;暖场&rdquo;脚本

上一篇文章我们讲到了关于如果采用IIS应用池回收技术来提高SharePoint的页面访问速度,今天来给大家讲一个SharePoint圈儿内"著名"的暖场脚本(Warm-up-script). 所谓暖场脚本,顾名思义,就是在一切正式的表演之前,先来给大家暖暖场,不至于使得大家感觉到尴尬和不自在.同理,其实就是帮助SharePoint实现访问提速,不至于访问卡顿和缓慢. 不知道大家有没有这样的感受,每天早上来上班,会发现第一次打开SharePoint的速度很慢,之后会好很多,这是什么原因呢