当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET 提高首页性能的十大做法

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

rpc服务器不可用,克拉玛依市,汐奴

前言
本文是我对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写入动态页面的内容到静态文件中。
复制代码 代码如下:

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;
}
//............
}

四、实现commonfilter类过滤viewstate、过滤namingcontainer、空白字符串,以及生成磁盘的缓存文件
我们传入response.filter的stream对象给commonfilter类:
首先,我们用先stream的write方法实现生成磁盘的缓存文件,代码如下,在这些代码中,只有初始化构造函数,write方法,close方式是有用的,其中filestream字段是生成静态文件的操作对象:
复制代码 代码如下:

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:
复制代码 代码如下:

// 过滤viewstate
private string viewstatefilter( string strhtml ) {
string matchstring1 = "type=\"hidden\" name=\"__viewstate\" id=\"__viewstate\"";
string matchstring2 = "type=\"hidden\" name=\"__eventvalidation\" id=\"__eventvalidation\"";
string matchstring3 = "type=\"hidden\" name=\"__eventtarget\" id=\"__eventtarget\"";
string matchstring4 = "type=\"hidden\" name=\"__eventargument\" id=\"__eventargument\"";
string positivelookahead1 = "(?=.*(" + regex.escape( matchstring1 ) + "))";
string positivelookahead2 = "(?=.*(" + 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;
}

以下是删除页面空白的方法:
复制代码 代码如下:

// 删除空白
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名称方法:
复制代码 代码如下:

// 过滤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方法:
复制代码 代码如下:

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过的页面。

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

// 更新文件
foreach ( var file in directory.getfiles( httpruntime.appdomainapppath + "temp" ) ) {
file.delete( file );
}

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

// 删除缓存
httpresponse.removeoutputcacheitem( "/default.aspx" );

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网