Library code snippets
Url Rewriting with Regex for ASP.NET 2.0
A new feature in ASP.NET 2.0 is it's built-in url rewriting support. When I looked into this new feature i found out it lacked regular expressions support, which is really the point of an Url Mapper. ScottGlu at his blog, explains the reason why the ASP.NET team didn't implement this featur, basically because they realized that a full featured version would want to take advantage of the next IIS 7.0 new features, specially the support for all content-types (images and directories).
Anyway, it's really simple to implement a Url Rewriting Module with Regex support in ASP.NET. I wrote a quick and simple HttpModule for this. The whole magic is done within a few lines within the HttpModule:
public void Rewrite_BeginRequest(object sender, System.EventArgs args) {
string strPath = HttpContext.Current.Request.Url.AbsolutePath;
UrlRedirection oPR = new UrlRedirection();
string strURL = strPath;
string strRewrite = oPR.GetMatchingRewrite(strPath);
if (!String.IsNullOrEmpty(strRewrite)) {
strURL = strRewrite;
} else {
strURL = strPath;
}
HttpContext.Current.RewritePath("~" + strURL);
}
The code is self explanatory. When a request that is processed by the ASP.NET engine, the module checks an XML for a regex match. I've seen many Url Rewriting engines that uses Web.config to store the matching rules but i prefer using an additional XML file. The rewriting rules file look like the following:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<urlrewrites>
<rule name="Category Page">
<url>/([a-zA-Z][\w-]{1,149})\.aspx</url>
<rewrite>/Default.aspx?Category=$1</rewrite>
</rule>
<rule name="Item Page">
<url>/([a-zA-Z][\w-]{1,149})/([a-zA-Z][\w-]{1,149})\.aspx</url>
<rewrite>/Default.aspx?Category=$1&Item=$2</rewrite>
</rule>
</urlrewrites>
The rule matching routine, wich is implemented in the GetMatchingRewrite() method is quite simple and lightweighted:
public string GetMatchingRewrite(string URL) {
string strRtrn = "";
System.Text.RegularExpressions.Regex oReg;
foreach (RedirectRule oRule in Rules) {
Reg = new Regex(oRule.URL);
Match oMatch = oReg.Match(URL);
if (oMatch.Success) {
strRtrn = oReg.Replace(URL, oRule.Rewrite);
}
}
return strRtrn;
}
I have uploaded a sample project that uses this rewriting engine. The HttpModule and it's helper classes are inside the App_Code folder. I hope you find this code useful, if you have any questions just leave a comment in this entry. Happy coding!
Related articles
Related discussion
-
Capture Video
by ess-image (23 replies)
-
DataGrid - How to display the content of a hidden TemplateField on mouseover
by DonCarnage (0 replies)
-
Problem when using TemplateField and ImageButton
by mhuff84 (14 replies)
-
How to prevent multiple login
by chunwei87 (2 replies)
-
problem sending Email message includes a picture
by renilative (3 replies)
Related podcasts
-
StackOverflow uses ASP.NET MVC - Jeff Atwood and his technical team
Scott chats with Jeff Atwood of CodingHorror.com and most recently, StackOverflow.com. Jeff and Joel Spolsky and their technical team have created a new class of application using ASP.NET MVC. What works, what doesn't, and how did it all go down?
Events coming up
-
Jul
7
DTC 70-528 Session 7: Chapter 12
Greenwood Village, United States
Due to lack of interest of the 5th Monday meetup, we will continue as originally scheduled. The topic of the night will be "Chapter 12 - Creating ASP.NET Mobile Web Applications", taught by RJ Hatch. It is a fairly small chapter, so we can discuss other topics as well. Pizza and beverages will be provided on a donation basis.
I hunted for two days to get this resolved... Here it is:
app.context.rewritepath(destinationurl, false);
the false tells the application not to reset the virtual path - otherwise the new url becomes the new virtual path which in turn give ~/default.aspx another meaning
I am using your example and am in a bit of a problem. the thing is I am getting redirected but if I am writing a url like so http://www.econn/page.aspx?id=10 & cat=20 how can i convert it to http://www.econn/page.aspx/id=10/cat=20 so that the parameters passed can be used on destination url
Plz help me with this
Hello!
I've tested the sample code but it doesn't work. When i run the code i get 404 - The resource cannot be found. Have I done anything wrong?
I figured out that removing the action attribute of the form fixed the problem:
heres an example:
public class Form : System.Web.UI.HtmlControls.HtmlForm
{
protected override void RenderAttributes(HtmlTextWriter writer)
{
writer.WriteAttribute(
"name", this.Name);
base.Attributes.Remove("name");
writer.WriteAttribute(
"method", this.Method);
base.Attributes.Remove("method");
this.Attributes.Render(writer);
base.Attributes.Remove("action");
if (base.ID != null)
writer.WriteAttribute(
"id", base.ClientID);
}
}
But there is another bug, i cant seem to google out..
My stylesheets and images isent shown, is there eny one who got the same problem? or is it something i am doing wrong ?
Hi..
Thanks for the tutorial..
But, when one of my controls makes an postback event, the url changes ex:
from:
http://localhost:1310/Modeltypes/Login.aspx
to:
http://localhost:1310/Modeltypes/Default.aspx?ModuleName=Login
And then the rewrite method sends moduleName=Default back, and sends the user to another page, "default"..
Am i doing something wrong?
sorry my poor english :), thanks in advance
Jacob Jensen
This thread is for discussions of Url Rewriting with Regex for ASP.NET 2.0.