ArticleDirectory
- Why rewrite the URL?
- Original URL ing in ASP. NET 2.0
- Processing Configuration section
- Parameters of the URL to be rewritten
- Rewrite URL
- Register the rewrite module in Web. config
- Use rewrite Module
- IIS configuration: replace. aspx with an extended rewrite Module
- Summary
This article describes a complete ASP. NET 2.0 URL rewriting solution. This solution uses regular expressions to define Rewrite Rules and solves some possible difficulties in generating a send-back event when accessing the page through virtual URLs.
Why rewrite the URL?
Apply the URL rewriting method to your ASP. NET applicationProgramThe two main reasons are availability and maintainability.
Availability
Everyone knows that, compared to the long query path with parameters that are difficult to identify, users prefer short and concise URLs. At any time, a path that is easy to remember and typed is more useful than adding to favorites. Second, when a browser's favorites is unavailable, remember the address is always better than entering keywords in the search engine for search and then searching. Compare the following two addresses:
|
(1) |
Http://www.somebloghost.com/Blogs/Posts.aspx? Year = 2006 & month = 12 & day = 10 |
|
(2) |
Http: // www. somebloghost.com/blogs/2006/12/10/ |
The first URL contains the query string. The second URL contains information that allows the user to clearly see what he is reading. It also makes it easier for the user to modify the content of the address bar, such: http://www.somehost.com/Blogs/2006/12.
Maintainability
In many web applications, developers often move pages from one directory to another. Let's assume that there are two available pages at the beginning:Http://www.somebloghost.com/Info/Copyright.aspxAndHttp://www.somebloghost.com/Support/Contacts.aspxLater, the developer moved copyright. aspx and contacts. aspx to the help directory, and the user needs to locate the favorite address. Although response. Redirect (New location), But what if there are hundreds of thousands of pages? The application contains a large number of invalid links.
Using URL rewriting allows users to modify configuration files only. This method allows developers to separate the web application logical structure from the physical structure.
Original URL ing in ASP. NET 2.0
ASP. NET 2.0 provides an out-of-the-box static URL ing solution for Web applications. This solution does not need to be written.CodeYou can map the old URLs to the new address in Web. config. To use URL ing, create a new urlmappings section in the system. web section of the web. config file and add the address to be mapped ("~ /"Points to the application root directory ):
<Urlmappings enabled = "true">
<Add url = "~ /INFO/Copyright. aspx "mappedurl = "~ /Help/Copyright. aspx "/>
<Add url = "~ /Support/contacts. aspx "mappedurl = "~ /Help/contacts. aspx "/>
</Urlmappings>
In this way, if you enterHttp://www.somebloghost.com/Support/Contacts.aspx, It will seeHttp://www.somebloghost.com/Help/Contacts.aspxBut he does not know that the page has been removed.
This solution is sufficient if only two pages are moved to another location. But it is not suitable for a dozen of pages to be relocated or for creating a clean URL. The other uses ASP. net's original URL ing technology is not very good: If contacts. when the elements contained in the ASPX page are sent back to the server (this is very likely), users will be surprised to find the addressHttp://www.somebloghost.com/Support/Contacts.aspxBut it becomesHttp://www.somebloghost.com/Help/Contacts.aspx
. This is because the ASP. net engine used the actual address of the page to modify the form.FormOfActionAttribute, so the form looks like the following:
<Form name = "formtest" method = "Post"
Action = "http://www.simple-talk.com/Help/Contacts.aspx" id = "formtest">
</Form>
In this case, URL ing is almost useless in ASP. NET 2.0. We should be able to use a ing rule to specify a series of similar URLs. The best solution is to use a regular expression (Wikipedia can view the overview, and in. net implementation can be viewed in msdn), but because ASP. NET 2.0 ing does not support regular expressions, so we need to develop a different scheme-URL rewriting module built in to URL ing. The best way is to create a reusable and simple configuration module for implementation. Obviously, we should create an HTTP module. (For details about the HTTP module, see the msdn magazine) it is also implemented in an independent program set. To make this Assembly easy to use, we should implement the configurability of this rewrite engine, that is, the rules can be specified in Web. config.
During the development process, we should enable or disable this rewrite module (for example, you have a bug that is hard to capture, and it may be caused by an incorrect rewrite module) in this way. in config, it is an option to enable or disable the configuration section of the rewrite module. In this way, the following is an example of a configuration section in Web. config:
<Rewritemodule>
<Rewriteon> true </rewriteon>
<Rewriterules>
<Rule source = "(\ D + )/"
Destination = "posts. aspx? Year = $1 & month = $2 & day = $3 "/>
<Rule source = "(. *)/default. aspx"
Destination = "default. aspx? Folder = $1 "/>
</Rewriterules>
</Rewritemodule>
In this way, all objects such:Http: // localhost/web/2006/12/10/This request will be redirected to posts. aspx with parameters in the internal part.
Note: Web. config is a well-structured XML file, which cannot be used in attribute values.&Symbol, so in the example, use & instead.
To use this rewrite module in the configuration file, you also need to register the section and specify the processing module. Add a configsections configuration section as follows:
<Configsections><Sectiongroup name = "modulessection">
<Section name = "rewritemodule" type = "rewritemodule.
Rewritemodulesectionhandler, rewritemodule "/>
</Sectiongroup>
</Configsections>
In this way, you can use the following code in the configsections section:
<Modulessection>
<Rewritemodule>
<Rewriteon> true </rewriteon>
<Rewriterules>
<Rule source = "(\ D +)/" Destination = "post. aspx? Year = $1 & month = $2 & day = $3 "/>
<Rule source = "(. *)/default. aspx" Destination = "default. aspx? Folder = $1 "/>
</Rewriterules>
</Rewritemodule>
</Modulessection>
Another thing we need to do in the process of developing the rewrite module is to allow passing parameters in the virtual path, as shown in the following code:Http://www.somebloghost.com/2006/12/10? Sort = DESC & sortby = Date. Therefore, we also need a solution to detect passing parameters through virtual URLs..
Next, let's create a class library. First, we need to reference the system. Web Assembly so that we can implement some special web-based functions. To enable our module to access web. config, you also need to reference the system. Configuration assembly.
Processing Configuration section
To handle the configuration in Web. config, we must create a class that implements the iconfigurationsectionhandler interface (For details, refer to msdn ). As follows:
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. configuration;
Using system. Web;
Using system. xml;
Namespace rewritemodule
{
Public class rewritemodulesectionhandler: iconfigurationsectionhandler
{
Private xmlnode _ xmlsection;
Private string _ rewritebase;
Private bool _ rewriteon;
Public xmlnode xmlsection
{
Get {return _ xmlsection ;}
}
Public String rewritebase
{
Get {return _ rewritebase ;}
}
Public bool rewriteon
{
Get {return _ rewriteon ;}
}
Public object create (Object parent,
Object configcontext,
System. xml. xmlnode Section)
{
// Set base path for rewriting module
// Application root
_ Rewritebase = httpcontext. Current. Request. applicationpath + "/";
// Process configuration section
// From web. config
Try
{
_ Xmlsection = Section;
_ Rewriteon = convert. toboolean (
Section. selectsinglenode ("rewriteon"). innertext );
}
Catch (exception ex)
{
Throw (new exception ("error while processing rewritemodule
Configuration section. ", ex ));
}
Return this;
}
}
}
The rewritemodulesectionhandler class initializes the xmlnode in Web. config by calling the create method. The selectsinglenode method of the xmlnode class is used to return the configuration value of the module.
Parameters of the URL to be rewritten
In the process like HTTP: // Www. somebloghost.com/blogs/gaidar /? Sort = ASC(This is a virtual URL with parameters.) When using a virtual URL, it is very important to clearly identify the parameters passed through the virtual path, as shown below:
<Rule source = "(. *)/default. aspx" Destination = "default. aspx? Folder = $1 "/>,
You may use the following URL:
Http: // www. somebloghost.com/gaidar /? Folder = blogs
Its effect is similar to the following:
Http: // www. somebloghost.com/blogs/gaidar/
To solve this problem, we need to wrap the 'virtual path parameter. You can use a static method to access the current parameter set:
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Collections. Specialized;
Using system. Web;
Namespace rewritemodule
{
Public class rewritecontext
{
// Returns actual rewritecontext instance
// Current request
Public static rewritecontext current
{
Get
{
// Look for rewritecontext instance in
// Current httpcontext. If there is no rewritecontextinfo
// Item then this means that rewrite module is turned off
If (httpcontext. Current. Items. Contains ("rewritecontextinfo "))
Return (rewritecontext)
Httpcontext. Current. items ["rewritecontextinfo"];
Else
Return new rewritecontext ();
}
}
Public rewritecontext ()
{
_ Params = new namevaluecollection ();
_ Initialurl = string. empty;
}
Public rewritecontext (namevaluecollection Param, string URL)
{
_ Initialurl = URL;
_ Params = new namevaluecollection (PARAM );
}
Private namevaluecollection _ Params;
Public namevaluecollection Params
{
Get {return _ Params ;}
Set {_ Params = value ;}
}
Private string _ initialurl;
Public String initialurl
{
Get {return _ initialurl ;}
Set {_ initialurl = value ;}
}
}
}
As you can see, the "virtual path parameters" can be accessed through the rewritecontext. Current set. All parameters are specified as virtual paths or pages, rather than query strings.
Rewrite URL
Next, let's try to rewrite it. First, we need to read the rewrite rules in the configuration file. Second, we need to check the parts that do not match the rules in the URL. If so, rewrite them and execute them on an appropriate page.
Create an httpmodule:
Class rewritemodule: ihttpmodule
{
Public void dispose (){}
Public void Init (httpapplication context)
{}
}
When we add the rewritemodule_beginrequest method to process URLs that do not comply with the rules, we need to check whether the given URL contains parameters and then call httpcontext. current. rewritepath to control and provide the appropriate ASP.. NET page.
Using system;
Using system. Collections. Generic;
Using system. text;
Using system. Web;
Using system. configuration;
Using system. xml;
Using system. Text. regularexpressions;
Using system. Web. UI;
Using system. IO;
Using system. Collections. Specialized;
Namespace rewritemodule
{
Class rewritemodule: ihttpmodule
{
Public void dispose (){}
Public void Init (httpapplication context)
{
// It is necessary
Context. beginrequest + = new eventhandler (
Rewritemodule_beginrequest );
}
Void rewritemodule_beginrequest (Object sender, eventargs E)
{
Rewritemodulesectionhandler CFG =
(Rewritemodulesectionhandler)
Configurationmanager. getsection
("Modulessection/rewritemodule ");
// Module is turned off in Web. config
If (! Cfg. rewriteon) return;
String Path = httpcontext. Current. Request. path;
// There us nothing to process
If (path. Length = 0) return;
// Load rewriting rules from web. config
// And loop through rules collection until first match
Xmlnode rules = cfg. xmlsection. selectsinglenode ("rewriterules ");
Foreach (xmlnode XML in rules. selectnodes ("rule "))
{
Try
{
RegEx Re = new RegEx (
Cfg. rewritebase + XML. attributes ["Source"]. innertext,
Regexoptions. ignorecase );
Match match = Re. Match (PATH );
If (match. Success)
{
Path = Re. Replace (
Path,
XML. attributes ["destination"]. innertext );
If (path. length! = 0)
{
// Check for querystring Parameters
If (httpcontext. Current. Request. querystring. Count! = 0)
{
// If there are query string papameters
// Then append them to current path
String Sign = (path. indexof ('? ') =-1 )? "? ":"&";
Path = path + sign +
Httpcontext. Current. Request. querystring. tostring ();
}
// New Path to rewrite
String rew = cfg. rewritebase + path;
// Save original path to httpcontext for further use
Httpcontext. Current. Items. Add (
"Originalurl ",
Httpcontext. Current. Request. rawurl );
// Rewrite
Httpcontext. Current. rewritepath (rew );
}
Return;
}
}
Catch (exception ex)
{
Throw (new exception ("Incorrect rule.", ex ));
}
}
Return;
}
}
}
This method must be registered:
Public void Init (httpapplication context)
{
Context. beginrequest + = new eventhandler (rewritemodule_beginrequest );
}
But this is only half done, because the rewrite module also needs to process the form sending and virtual path parameter sets, and you will find that you have not processed this in this Code. Let's put the virtual path parameter aside first, and correctly handle the most important sending back.
If we run the above Code and view the HTML of ASP. NETSource codeAction will find that it actually contains an ASP. NET actual path page. For example, we use the page ~ /Posts. aspx to process the imageHttp: // www. somebloghost.com/blogs/2006/12/10/default.aspxAction = "/posts. aspx" is found ". This means that the user does not use the virtual path for sending back, but uses the actualHttp: // www. somebloghost.com/blog.aspx. This is not what we need. Therefore, you need to add a piece of code to process these unwanted results.
First, we need to register and implement another method in httpmodule:
Public void Init (httpapplication context)
{
// It is necessary to
context. beginrequest + = new eventhandler (
rewritemodule_beginrequest);
context. prerequesthandlerexecute + = new eventhandler (
rewritemodule_prerequesthandlerexecute);
}
void upload (Object sender, eventargs e)
{
httpapplica Tion APP = (httpapplication) sender;
If (App. Context. currenthandler is page) &
app. Context. currenthandler! = NULL)
{
page Pg = (PAGE) app. context. currenthandler;
PG. preinit + = new eventhandler (page_preinit);
}
This method checks whether the user has requested a normal ASP. NET page, and then adds a processing process for the preinit event of the page. Here, rewritecontext will process the actual parameters, and then rewrite the URL twice. Secondary rewriting is required so that ASP. Net can use a virtual path in the Action attribute of its form.
Void page_preinit (Object sender, eventargs E)
{
// Restore internal path to original
// This is required to handle postbacks
If (httpcontext. Current. Items. Contains ("originalurl "))
{
String Path = (string) httpcontext. Current. items ["originalurl"];
// Save query string parameters to context
Rewritecontext con = new rewritecontext (
Httpcontext. Current. Request. querystring, PATH );
Httpcontext. Current. items ["rewritecontextinfo"] = con;
If (path. indexof ("? ") =-1)
Path + = "? ";
Httpcontext. Current. rewritepath (PATH );
}
}
Finally, let's take a look at the three classes in our rewrite Module assembly:
Register the rewrite module in Web. config
To use the rewrite module, you must register the rewrite module in the httpmodules section of the configuration file, as shown below:
<Httpmodules>
<Add name = "rewritemodule" type = "rewritemodule. rewritemodule, rewritemodule"/>
</Httpmodules>
Use rewrite Module
When using the rewrite module, note the following:
- In the web. it is impossible to use some special characters in config because it is a well-structured XML file. Therefore, you can only use HTML-encoded characters instead, for example, use & instead &.
- To use relative paths in your Aspx, you must call the resolveurl method in the HTML Tag, for example, .
- Bear in mind the greediness of regular expressions and put rewriting rules to Web. config in order of their greediness, for instance:
<Rule source = "directory/(. *)/(. *). aspx"
Destination = "directory/item. aspx?
Source = $1 & year = $2 & validtill = $3 & sales = $4 "/>
<Rule source = "directory/(. *). aspx"
Destination = "directory/items. aspx?
Source = $1 & year = $2 & validtill = $3 "/>
<Rule source = "directory/(. *)/(. *). aspx"
Destination = "directory/sourceyear. aspx?
Source = $1 & year = $2 & "/>
<Rule source = "directory/(. *). aspx"
Destination = "directory/source. aspx? Source = $1 "/>
- If you want to use rewritemodule on the page instead of. aspx, you must configure it in IIS to map to the request page using the expected extension, as described in the following section:
IIS configuration: replace. aspx with an extended rewrite Module
Replace it with an extended rewrite module. aspx (such. HTML or. XML), IIS must be configured to map these extensions to ASP. net engine (Asp.. Net ISAPI extension ). To perform these settings, log on as an administrator.
Open the IIS console and select the virtual path of the site you want to configure:
Windows XP (IIS 5)
Virtual directory "RW"
Windows 2003 Server (IIS 6)
Default web site
Click Configuration... on the virtual path label... Button (or select the Home Directory label if you want to map the entire site ).
Windows XP (IIS 5)
Windows 2003 Server (IIS 6)
Next, click the Add button and enter an extension. You also need to specify an ASP. net isapi extension. Note that the check box of the option is removed to check whether the file exists.
If you want to map all extensions to ASP. net, for IIS 5 on Windows XP, you only need to set. * To ASP. net ISAPI, but it is different for IIS 6. Click "add" and specify ASP.. Net ISAPI extension.
Summary
Now, we have created a simple but very powerful ASP.. Net rewrite module, which supports URLs and page sending back based on regular expressions. This solution is easy to implement and provides examples for users, it can replace the query string parameter with a brief and neat URL. To use this module, simply reference the rewritemodule in your application, and add several lines of code in the web. config file so that the URLs you do not want to display are replaced by regular expressions. This rewrite module is easy to deploy, because you only need to modify any "virtual" url in Web. config. If you need to perform a test, you can also disable the rewrite module.
To have an in-depth understanding of the rewrite module, you can view the original code provided in this Article. I believe you will find that this is a better experience than the original ing provided by ASP. NET.