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!

You might also like...

Comments

Xavier Larrea

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The question of whether computers can think is just like the question of whether submarines can swim.” - Edsger W. Dijkstra