Two methods to convert ASP. NET Dynamic pages to static pages-methods to convert dynamic pages to HTML static pages

Source: Internet
Author: User

ASP. NET: (Welcome to discuss)

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

To discuss the implementation method, I will summarize the following two mainstream methods:

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 of myconvert.
///
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
Showarticle

Title

Content

Author

Note: 1. The news folder must grant the write permission to the Asp.net user. 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.

In this case, you can enter HTML tags in the entire project.
Disadvantage: This method is not flexible enough to use 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 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 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 younger brother is still a cainiao. Please comment on them.

 

For the second method you mentioned, you need to use the "automatically search for static files" method. In the page_init event of the page, first check whether there are static files in the local device. If yes, directly redirect (for example, server. Transfer (...) to that page. When you need to recreate a page, you can delete its static files. The page will be automatically rebuilt the next time you access the page.

However, no matter the first or second type, I don't think it makes much sense, especially compared with page buffering or Ajax.

If you convert all URLs to static files, static files are really static. That is, when Asp.net is deleted from the server, it still allows you to browse the entire website through the Web server.

I did this.

Use the method you mentioned to replace the news content.

I also used the following generation method, but there is a problem.

If you bind a database with a DataGrid or datalist, the generated static page style table is faulty. Seriously

Public class getpagehtml: system. Web. UI. Page
{
Protected system. Web. UI. webcontrols. Button webclientbutton;
Protected system. Web. UI. webcontrols. Button webrequestbutton;
Protected system. Web. UI. webcontrols. textbox contenthtml;
Protected system. Web. UI. webcontrols. textbox urltext;
Private string pageurl = "";

Private void page_load (Object sender, system. eventargs E)
{}

# Region web form designer generated code
Override protected void oninit (eventargs E)
{
Initializecomponent ();
Base. oninit (E );
}

///
/// The designer supports the required methods-do not useCodeEdit Editor
/// Content of this method.
///
Private void initializecomponent ()
{
This. webclientbutton. Click + = new system. eventhandler (this. webclientbutton_click );
This. webrequestbutton. Click + = new system. eventhandler (this. webrequestbutton_click );
This. Load + = new system. eventhandler (this. page_load );
}
# Endregion

Private void webclientbutton_click (Object sender, system. eventargs E)
{
Pageurl = urltext. text;
WebClient WC = new WebClient ();
WC. Credentials = credentialcache. defaultcredentials;

/// Method 1:
Byte [] pagedata = WC. downloaddata (pageurl );
Contenthtml. Text = encoding. Default. getstring (pagedata );

/// Method 2:
/// **************** Code start **********
/// Stream resstream = WC. openread (pageurl );
/// Streamreader sr = new streamreader (resstream, system. Text. encoding. Default );
/// Contenthtml. Text = Sr. readtoend ();
/// Resstream. Close ();
/// ***************** Code end ********
///
WC. Dispose ();
}

Private void webrequestbutton_click (Object sender, system. eventargs E)
{
Pageurl = urltext. text;
Webrequest request = webrequest. Create (pageurl );
Webresponse response = request. getresponse ();
Stream resstream = response. getresponsestream ();
Streamreader sr = new streamreader (resstream, system. Text. encoding. Default );
Contenthtml. Text = Sr. readtoend ();
Resstream. Close ();
Sr. Close ();
}
}

I implemented it using XML + XSL.

Define the data to be retrieved in the XML document

ProgramTraverse the XML document and add the retrieved data to the current XML document.

Use XSL to convert to HTML and Output

Converting XSL to HTML is CPU-consuming. If the access volume is large, you can use. Net remoting to place XSL to HTML on another server for processing.

We recommend that you use ihttphandlefactory to capture the URL address and then generate the page, which is super simple.
Public class httphand: ihttphandlerfactory
{
# Region create an HTTP Factory

Public void releasehandler (ihttphandler handler)
{

}

Public ihttphandler gethandler (httpcontext context, string requesttype, string URL, string pathtranslated)
{
// Obtain the name of the randomly defined file, including the extension
String name = URL. substring (URL. lastindexof ('/') + 1 );
String filename = Name. substring (0, name. lastindexof ('.'));
Filename = "commonfactory." + filename;

Object OBJ = NULL; // a type used to convert ihttphandler to an abstract type

// Create an HTTP
Try
{
Type TP = type. GetType (filename );
OBJ = system. activator. createinstance (TP );
}
Catch
{

}
Return (ihttphandler) OBJ;
}

# Endregion
}

-----------------------------------------------------------------------
Public class loginout: ihttphandler
{

Sqlfactory. Operation opea = new sqlfactory. Operation ();
Public void processrequest (httpcontext context)
{
If (context. User. Identity. Name! = String. Empty)
{
String Path = context. Request. querystring ["p"];

// CLEAR user logon table information
Opea. voiddelsinlogin (context. User. Identity. Name );
Opea. voidaddwork (context. User. Identity. Name + "", "");
Sec. formsauthentication. signout ();
Alertstr. alertbackwindow (context. response, "logout successful. Come back! ", PATH );

}
Else
{
Opea. voidaddwork ("anonymous user logout", "logout failed, cause: No Logon ");
Alertstr. alertbackwindow (context. response, "unable to log out without logon", context. request );
}
}

Public bool isreusable
{
Get
{
// Todo: Add loginout. isreusable getter implementation
Return true;
}
}

 

}

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.