Use urlrewrite and Asp.net to dynamically generate HTM pages [favorites]

Source: Internet
Author: User
When I was working on a project some time ago, I was always looking for a method to dynamically generate HTM pages. The configuration was simple and had nothing to do with the project.
I finally found it. I only need to perform simple configuration in Web. config to dynamically generate static pages without affecting URL redirection. In web. config, You need to note the configuration items <configuration>, <rewriteconfig>, <? XML version = "1.0" encoding = "UTF-8"?>
<! --
Note: In addition to manually editing this file, you can also use
Web management tools to configure application settings. You can use
"Website"-> "asp" . NetConfiguration option.
The complete list of settings and comments is displayed in
In machine. config. Comments, this file is usually located in
/ Windows/Microsoft . Net/Framework/v2.x/config
-->
<Configuration>

<! -- Rul rewrite start -->
<Configsections>
<Section name = "rewriterconfig" type = "urlrewriter. config. rewriterconfigserializersectionhandler, urlrewriter"/>
</Configsections>
<Rewriterconfig>
<Rules>
<! -- Address rewriting rule -->
<! -- Homepage, go to static page -->
<Rewriterrule>
<Type> static </type>
<Lookfor> ~ /Default/. aspx </lookfor>
<Sendto> ~ /Default.htm </sendto>
</Rewriterrule>
<! -- Level 2 page, go to dynamic page -->
<Rewriterrule>
<Type> dynamic </type>
<Lookfor> ~ /LIST/. aspx </lookfor>
<Sendto> ~ /Show. aspx </sendto>
</Rewriterrule>
</Rules>
</Rewriterconfig>
<! -- Rul rewrite ended -->

<Appsettings/>
<Connectionstrings/>
<System. Web>
<! --
Set compilation DEBUG = "true" to insert the debugging symbol
Compiled pages. However, this
Performance is affected, so this value is only available during development.
Set to true.
-->
<Httpmodules>
<! -- URL rewriting -->
<Add type = "urlrewriter. modulerewriter, urlrewriter" name = "modulerewriter"/>
</Httpmodules>

<Httphandlers>
<! -- Generate static pages -->
<Add verb = "*" Path = "*. aspx" Validate = "false" type = "urlrewriter. rewriterfactoryhandler, urlrewriter"/>
</Httphandlers>

<Compilation DEBUG = "false"/>
<! --
In the <authentication> section, you can configure
SecurityAuthentication mode,
To identify the user.
-->
<Authentication mode = "forms"/>
<! --
If an unprocessed error occurs during request execution,
You can configure the corresponding processing steps in the <mermerrors> section. Specifically,
This section allows developers to configure
HTML error page to be displayed
To replace the error stack trace.

<Customerrors mode = "remoteonly" defaultredirect = "genericerrorpage.htm">
<Error statuscode = "403" Redirect = "noaccess.htm"/>
<Error statuscode = "404" Redirect = "filenotfound.htm"/>
</Customerrors>
-->
<Globalization requestencoding = "UTF-8" responseencoding = "UTF-8"/>
</System. Web>
</Configuration>
Two key classes are modulerewriter and rewriterfactoryhandler.
The modulerewriter class is used for URL redirection. The Code is as follows:
Modulerewriter
Using system;
Using system. Text. regularexpressions;
Using system. configuration;
Using urlrewriter. config;
Using system. Data;
Using system. Web;
Using system. Web. UI;
Namespace urlrewriter
{
/** // <Summary>
/// Provides a rewriting httpmodule.
/// </Summary>
Public class modulerewriter: basemodulerewriter
{
/** // <Summary>
/// This method is called during the module's beginrequest event.
/// </Summary>
/// <Param name = "requestedrawurl"> the rawurl being requested (required des path and querystring). </param>
/// <Param name = "app"> the httpapplication instance. </param>
Protected override void rewrite (string requestedpath, system. Web. httpapplication APP)
{
// Only valid for the file suffix ASPX page
If (requestedpath. indexof (". aspx ")! =-1)
{
Httpcontext = app. context;

// Get the configuration rules
Rewriterrulecollection rules = rewriterconfiguration. getconfig (). Rules;

// Iterate through each rule
For (INT I = 0; I <rules. Count; I ++)
{
// Get the pattern to look for, and resolve the URL (convert ~ Into the appropriate directory)
String lookfor = "^" + rewriterutils. resolveurl (httpcontext. Request. applicationpath, rules [I]. lookfor) + "$ ";

// Create a RegEx (note that ignorecase is set)
RegEx Re = new RegEx (lookfor, regexoptions. ignorecase );

// See if a match is found
If (Re. ismatch (requestedpath ))
{
// The ASPX page is redirected to the HTM page and the HTTP data transmission mode is "get"
If (rules [I]. type = webtype. Static & App. Context. Request. requesttype = "get ")
{
// Static Page path
String htmlweb = rewriterutils. resolveurl (httpcontext. Request. applicationpath, rules [I]. sendto );
// Last modification time of the Static Page
Datetime dt = system. Io. file. getlastwritetime (httpcontext. server. mappath (htmlweb ));
// Compare the current time with the static page generation time. If the time is less than one hour, redirect to the static page
If (datetime. Compare (datetime. Now. addhours (-1), DT) <= 0)
{
Requestedpath = htmlweb;
}
}
Else
{
Requestedpath = Rules [I]. sendto;
}

// Rewrite the URL
Rewriterutils. rewriteurl (httpcontext, requestedpath );
Break; // exit the For Loop
}
}
}
}

}
}
The createhtmfactoryhandler class is used to generate static pages. The Code is as follows:
Createhtmfactoryhandler
Using system;
Using system. IO;
Using system. Web. UI;
Using system. Web;
Using urlrewriter. config;
Using system. configuration;
Using system. Text. regularexpressions;

Namespace urlrewriter
{
/** // <Summary>
/// Generate a static page based on the Web. config configuration information
/// </Summary>
Public class createhtmfactoryhandler: ihttphandlerfactory
{
/** // <Summary>
///
/// </Summary>
/// <Param name = "context"> httpcontext class instance, which provides internal ServerReferences of objects (such as request, response, session, and server) </param>
/// <Param name = "requesttype"> HTTP data transmission method (get or post) used by the client </param>
/// <Param name = "url"> rawurl of the requested resource. </Param>
/// <Param name = "pathtranslated"> physicalapplicationpath of the requested resource </param>
/// <Returns> return the instance of the class implementing the ihttphandler interface </returns>
Public Virtual ihttphandler gethandler (httpcontext context, string requesttype, string URL, string pathtranslated)
{
If (requesttype = "get ")
{
// Get the configuration rules
Rewriterrulecollection rules = rewriterconfiguration. getconfig (). Rules;

// Iterate through each rule
For (INT I = 0; I <rules. Count; I ++)
{
// Get the pattern to look for, and resolve the URL (convert ~ Into the appropriate directory)
String lookfor = "^" + rewriterutils. resolveurl (context. Request. applicationpath, rules [I]. lookfor) + "$ ";

// Create a RegEx (note that ignorecase is set)
RegEx Re = new RegEx (lookfor, regexoptions. ignorecase );

// See if a match is found
If (Re. ismatch (URL) & rules [I]. type = webtype. Static)
{
// Obtain the physical path of the static page to be generated
String physicsweb = context. server. mappath (rewriterutils. resolveurl (context. Request. applicationpath, rules [I]. sendto ));
// Set the response Filter
Context. response. Filter = new responsefilter (context. response. filter, physicsweb );
Break;
}
}
}
// Get the compiled instance
Return pageparser. getcompiledpageinstance (URL, pathtranslated, context );
}

Public Virtual void releasehandler (ihttphandler handler)
{
}
}
}
The above are two main classes and some auxiliary classes. TestThe project is attached with the source code and examples.
Click here Download: Source code and example
I am modifying an open-source project (urlrewrite) to implement the above functions. For more information about urlrewrite, see URL rewriting in ASP. NET.

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.