Converting dynamic pages to static pages in ASP. NET

Source: Internet
Author: User

Because of the differences between the search engine's ASPX page indexing and HTML page indexing rates and the problems with page resource usage, we often need to implement dynamic and static conversion of aspx pages. There are also many people on the Internet

I will discuss its implementation methods. Practice The following two mainstream methods are summarized as follows:

Method 1 :
To use template conversion, follow these steps:
1. Create a myconvert. CS File
Using system;
// Remember to add the following three references
Using system. text;
Using system. Web;
Using system. IO;
Namespace tesconvert
{
/// <Summary>
/// Summary of myconvert.
/// </Summary>
Public class myconvert
{
Public myconvert ()
{
//
// Todo: add the constructor logic here
//
}
Public bool writefile (string strtext, string strcontent, string strauthor)
{
String Path = httpcontext. Current. server. mappath ("/tesconvert/news/"); // defines the HTML file storage path
Encoding code = encoding. getencoding ("gb2312"); // defines the text encoding.
// Read the Template File
String temp = httpcontext. Current. server. mappath ("/tesconvert/text.html ");
Streamreader sr = NULL;
Streamwriter Sw = NULL;
String STR = "";
Try
{
Sr = new streamreader (temp, Code );
STR = Sr. readtoend (); // read the file
}
Catch (exception exp)
{
Httpcontext. Current. response. Write (exp. Message );
Httpcontext. Current. response. End ();
Sr. Close ();
}
String htmlfilename = path + datetime. Now. tostring ("yyyymmddhhmmss") + ". html ";
// Replace content
// At this time, the template file has been read into the variable named STR
STR = Str. Replace ("showarticle", strtext); // showarticle on the template page
STR = Str. Replace ("title", strtext );
STR = Str. Replace ("content", strcontent );
STR = Str. Replace ("author", strauthor );
// Write an object
Try
{
Sw = new streamwriter (htmlfilename, false, Code );
Sw. Write (STR );
Sw. Flush ();
}
Catch (exception ex)
{
Httpcontext. Current. response. Write (ex. Message );
Httpcontext. Current. response. End ();
}
Finally
{
Sw. Close ();
}
Return true;
}
}
}
2. testnews. aspx file:
Three buttons and textbox are added: tbx_title, tbx_content, tbx_author, and a button: btn_addnews.
Testnews. aspx. CS File
Private void btn_addnews_click (Object sender, system. eventargs E)
{
Myconvert hover = new myconvert ();


If (hover. writefile (this. txb_title.text.tostring (), server. htmldecode (this. txb_content.value), this. txb_author.text.tostring ()))
{
Response. Write ("added successfully ");
}
Else
{
Response. Write ("An error occurred while generating HTML! ");
}
}
32.16.html template text.html File
<Head> showarticle <Body>
Title <br>
Content <br>
Author
</Body>
Note: 1. asp must be assigned to the news folder . Net Write Permission. This is a simple implementation example. The actual project must first save the data to the database

The URL of the HTML file under the database. 2. By default, we cannot add HTML syntax to textbox or textarea. the config file must be modified.

<System. Web> Add <pages validaterequest = "false"/> below, but in this case, HTML tags can be entered in the entire project, and other parties are unknown.
Disadvantage: Method It is about using httpmodule to change the page content before response after Asp.net generates all the page content and performs operations on the page content before the output content. It is not flexible enough.

, It is more labor-intensive to modify response in each line.

Method 2:
Rewriting attributecollection. Render is more flexible (msdn says: "In the rendering phase, all ASP . NET mobile device adapters all use an object called a text writer

To write their output. The text writer object is created from the textwriter base class .")
You can write a base class, such:
Public class basepage: system. Web. UI. Page
{
Public basepage ()
{
}
Protected override void render (system. Web. UI. htmltextwriter writer)
{
String name = request. url. absolutepath. substring (1, request. url. absolutepath. Length-1). Replace ("aspx", "htm ");
String newurl = "";
If (name. indexof ("/")> 0)
{
Newurl = server. mappath ("../") + name;
}
Else
{
Newurl = server. mappath ("./") + name;
}
Memorystream MS = new memorystream ();
Streamwriter sww = new streamwriter (MS );
Streamwriter SWR = new streamwriter (newurl );
System. Web. UI. htmltextwriter htmlw = new htmltextwriter (SWR );
Base. Render (htmlw );
Htmlw. Flush ();
Htmlw. Close ();
String strll = system. Text. encoding. utf8.getstring (Ms. toarray ());
Response. Write (strll );
Response. Redirect (request. url. absoluteuri. Replace ("aspx", "htm"), true );
}
}
Then inherit from the page where you want to generate a static page.

Note: This method is to perform another conversion after the Asp.net generation is complete.
Disadvantage: I think it should be An ASPX page with frequent post operations.

The following information is found on the network: Code :

There are many ways to convert dynamic pages to static pages in ASP. NET. Based on actual needs, I found someSource codeAnd make modifications. Write the modified Code and description.

The following is a page conversion class, which is implemented through the static function changfile (), and the conversion from dynamic pages to static pages.

Using system;
Using system. Data;
Using system. configuration;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. text;
Using system. IO;

/** // <Summary>
/// Summary description for htmlproxy
/// </Summary>
Public class htmlproxy
...{
Public htmlproxy ()
...{
}
Public static bool changefile (int id)
...{
String filename = httpcontext. Current. server. mappath ("post _" + ID + ". html ");
// Try to read an existing file
Stream ST = getfilestream (filename );
// If the file exists and is read successfully
If (st! = NULL)
...{
Using (ST)
...{
Streamtostream (St, httpcontext. Current. response. outputstream );
Return true;
// Response. End ();
}
}
Else
...{
Stringwriter Sw = new stringwriter ();
Httpcontext. Current. server. Execute ("forumdetail. aspx? PID = "+ id, SW );

String content = Sw. tostring ();
// Write the file
Try
...{
Using (filestream FS = new filestream (filename, filemode. Create, fileaccess. Write, fileshare. Write ))
...{
Using (streamwriter STW = new streamwriter (FS, httpcontext. Current. response. contentencoding ))
...{
STW. Write (content );
}
}
Return true;
}
Catch... {return false ;}
}
}

Private Static stream getfilestream (string filename)
...{
Try
...{
Datetime dt = file. getlastwritetime (filename );
Timespan Ts = DT-datetime. now;
If (TS. totalhours> 1)
...{
// Expire in one hour
Return NULL;
}
Return new filestream (filename, filemode. Open, fileaccess. Read, fileshare. Read );
}
Catch... {return NULL ;}
}

Static public void streamtostream (Stream SRC, stream DST)
...{
Byte [] Buf = new byte [1, 4096];
While (true)
...{
Int c = SRC. Read (BUF, 0, Buf. Length );
If (C = 0)
Return;
DST. Write (BUF, 0, C );
}
}
}
In the page file, the background code of forurl. aspx is as follows:

 

Protected void page_load (Object sender, eventargs E)
...{
Try
...{
Int id = int. parse (request. querystring ["PID"]);
If (htmlproxy. changefile (ID ))
...{
Response. Redirect ("post _" + ID + ". html ");
}
Else
...{
Response. Redirect ("post. aspx? PID = "+ id );
}
}
Catch ...{
}
}

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.