ASP.NET页面性能优化的十大做法
四、实现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* + positiveLookahead1 + "(.*?), opt), new Regex("\\s*"\\s*" + positiveLookahead2 + "(.*?), opt), new Regex("\\s*"\\s*" + positiveLookahead3 + "(.*?), opt), new Regex("\\s*"\\s*" + positiveLookahead3 + "(.*?), opt), new Regex("\\s*"\\s*" + positiveLookahead4 + "(.*?), opt) }; foreach ( Regex re in arrRe ) { strHTML = re.Replace( strHTML, "" ); } return strHTML; }"\\s*"
以下是删除页面空白的方法:
// 删除空白 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( "//", "" ); 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" );
到此,我们实现了针对一个页面的性能,重点是载入速度的提高的一些做法,希望对大家有用~!
[第1页][第2页]