Top 10 Ways to Improve homepage Performance Using ASP. NET

Source: Internet
Author: User
Tags md5 encryption

Preface
This article is my Practice of Improving the loading speed of ASP. NET pages. These practices are divided into the following parts:
1. Use the HTTP module to control the page lifecycle.
2. Customize response. Filter to get the static content (disk cache) of the dynamic page generated by the output stream ).
3. gzip compression on the page.
4. outputcache program outputs the page cache.
5. Delete blank strings on the page. (Similar to Google)
6. Completely Delete the viewstate.
7. Delete the junk namingcontainer generated by the server control.
8. Use scheduled tasks to generate pages on time. (This article does not include the implementation of this practice)
9. JS, CSS compression, merging, caching, and image caching. (Limited Article Length, this article does not include the implementation of this practice)
10. cache corruption. (Excluding implementation of 9th practices)

In response to the above practices, we first need an HTTP module, which is the portal and core of the entire page process.

1. Customize response. Filter to get the static content of the dynamic page generated by the output stream (disk cache)
The following Code We can see that we use request. rawurl is the basis for caching, because it can contain any querystring variable. Then, we use MD5 encryption to obtain the variable of the local file name on the server, and instantiate a fileinfo to operate the file, if the last file generation time is less than 7 days, we use. the transmitfile method added by net2.0 sends the static content of the stored file to the browser. If the file does not exist, we will pass the Stream Obtained by response. filter to the commonfilter class and use filestream to write the dynamic page content to the static file. Copy code The Code is as follows: 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 ();
}
}
}

Ii. Page gzip Compression
For gzip compression on pages, almost every explanation of high-performance WEB Program Because gzip compression can reduce the number of bytes sent by the server, it can make the customer feel that the speed of the webpage is faster and the bandwidth usage is reduced. Of course, the client browser also supports it. Therefore, if the client supports gzip, we will send the content compressed by gzip. If not, we will directly send the content of the static file. Fortunately, modern browsers such as ie6.7.8.0 and Firefox support gzip.
To implement this function, we need to rewrite the above application_beginrequest event: Copy code The Code is as follows: 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 );
// Use page Compression
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
}

Iii. outputcache Programming Method output page Cache
The embedded outputcache cache of ASP. NET can cache content in three places: Web server, proxy server, and browser. ASP. net After msil, first write the result to the output cache, and then send it to the browser. When the user accesses the page in the same path, Asp. net will directly send the cached content without passing through. the process of aspx compilation and execution of msil. Therefore, although the program's own efficiency is not improved, the page loading speed is improved.

To implement this function, we continue to rewrite the above application_beginrequest event. After transmitfile, We cache the page in this path in outputcache programming mode:Copy codeThe Code is as follows: Private void application_beginrequest (Object sender, eventargs e ){
//.............
If (datetime. Now. Subtract (file. lastwritetime). totalminutes <5 ){
Response. transmitfile (PATH );
// Add the outputcache cache header and cache it on the client
Response. cache. setexpires (datetime. Now. addminutes (5 ));
Response. cache. setcacheability (httpcacheability. Public );
Response. End ();
Return;
}
//............
}

4. Implement commonfilter class to filter viewstate, filter namingcontainer, blank string, and generate disk cache files
We passed the stream object of response. filter to the commonfilter class:
First, we use the first stream write method to generate disk cache files. The Code is as follows. In these Code, only the initialization constructor, the write method, and the close method are useful, the filestream field is the operation object for generating static files: Copy code The Code is as follows: 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 ();
}
}
}
}

Then we use the regular expression to completely delete viewstate:Copy code The Code is as follows: // filter 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;
}

To delete a blank page, follow these steps: Copy code The Code is as follows: // Delete the blank space
Private RegEx tabsre = new RegEx ("\ t", regexoptions. Compiled | regexoptions. multiline );
Private RegEx carriagereturnre = new RegEx (">\\ r \ n <", regexoptions. Compiled | regexoptions. multiline );
Private RegEx carriagereturngfere = 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 = carriagereturnsaid Fere. Replace (HTML ,"");
While (multiplespaces. ismatch (HTML ))
Html = multiplespaces. Replace (HTML ,"");
Html = spacebetweentags. Replace (HTML, "> <");
Html = html. Replace ("// <! [CDATA [","");
Html = html. Replace ("//]> ","");
Return HTML;
}

Delete ASP. net control spam uniqueid name method: copy Code the code is as follows: // filter 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);
}< br> else {
return M. value;
}< BR >});
return HTML;
}

Finally, we integrate the above filtering methods into the write method of the commonfilter class:Copy codeThe Code is as follows: public override void write (byte [] buffer, int offset, int count ){
// Convert the buffer into a string
Byte [] DATA = new byte [count];
Buffer. blockcopy (buffer, offset, Data, 0, count );
String html = system. Text. encoding. utf8.getstring (buffer );
//
// The following Integrated filtering methods
//
Html = namingcontainerfilter (HTML );
Html = viewstatefilter (HTML );
Html = whitespacefilter (HTML );
Byte [] outdata = system. Text. encoding. utf8.getbytes (HTML );
// Write data to the disk
_ Cachestream. Write (outdata, 0, outdata. getlength (0 ));
_ Responsestream. Write (outdata, 0, outdata. getlength (0 ));
}

5. cache corruption
After the implementation of the above program, the webpage has been cached on the client. If the user accesses the page cached by the website, the page will load the page at zero request speed. However, if some data is updated in the background, the foreground users cannot view the latest data in time. To change this situation, we must destroy the cache. Based on the above program, we only need to perform two steps to destroy the cache: update the temporary files on the server and delete the pages that have been replaced by outputcache.

To update a file on the server, you only need to delete this file. This file is automatically generated when a user visits this page for the first time. Of course, you can also delete the file with a program and then generate it:Copy codeThe Code is as follows: // update the file
Foreach (var file in directory. getfiles (httpruntime. appdomainapppath + "Temp ")){
File. Delete (File );
}

To delete the cache items associated with outputcache, the Code is as follows. We only need to ensure that the parameters of this method indicate that the absolute path of the page is correct and that the relative path like ../cannot be used:Copy codeThe Code is as follows: // Delete the cache
Httpresponse. removeoutputcacheitem ("/default. aspx ");

At this point, we have implemented the performance for a page, focusing on improving the loading speed and hope it will be useful to you ~!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.