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!

Comments

  1. 07 Jan 2009 at 23:10
    To automize url rewriting procedure you can use [http://dotnetguts.blogspot.com/2008/07/url-rewriting-with-urlrewriternet.html](http://dotnetguts.blogspot.com/2008/07/url-rewriting-with-urlrewriternet.html)
  2. 02 May 2007 at 21:40

    ernestomodena wrote:
    I have the same problem it is not seeing mine js files and css files have anyone found the solution for this

    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

  3. 03 Apr 2007 at 07:41
    hi,
        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




  4. 08 Jan 2007 at 13:11
    I have the same problem it is not seeing mine js files and css files have anyone found the solution for this

  5. 05 Jun 2006 at 15:40

    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?



  6. 30 Apr 2006 at 13:09

    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 ?



































  7. 29 Apr 2006 at 21:35

    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




















  8. 01 Jan 1999 at 00:00

    This thread is for discussions of Url Rewriting with Regex for ASP.NET 2.0.

Leave a comment

Sign in or Join us (it's free).

Xavier Larrea

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

Want to stay in touch with what's going on? Follow us on twitter!