Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET
Article

URL Rewriting in ASP.NET 2.0

Rate me:
Please Sign up or sign in to vote.
3.08/5 (9 votes)
11 Dec 2007CPOL3 min read 89K   48   10
How to implement URL rewriting and improve your SEO rankings.

Introduction

In this article, you will learn about URL rewriting in ASP.NET 2.0. URL rewriting was originally introduced by Apache as an extension called mod_rewrite. The concept of URL rewriting is simple. It allows you to rewrite those ugly URLs into better URLs, and hence it will perform better in SEO.

Most search engines will ignore dynamic URLs such as the ones ending with a querystring, e.g., http://www.worldofasp.net/displayproduct.aspx?ID=10. Therefore, if you like to have more hits and traffic from search engines, consider rewriting all those querystring URLs into normal URLs.

If you rewrite the URL above, you can actually rewrite it into a more readable format, e.g., http://www.worldofasp.net/product10.aspx. Or, you can rewrite it to http://www.worldofasp.net/product/10.aspx.

Search engine robots will think that your dynamic page is a normal page, and therefore will crawl your page, and thus your page will have better search results. If you check the pages in Worldofasp.net or CodeProject.com, you can see that the web developers have used URL rewriting techniques.

Main

Microsoft .NET Framework 2.0 comes with a limited URL rewriting library support, and you have to write your own URL rewriting engine if you need complex URL rewriting for your website. The simplest URL rewriting that you can achieve in seconds is by copying and pasting the code below to your global.asax file:

void Application_BeginRequest(Object sender, EventArgs e) 
{{
 String strCurrentPath;
 String strCustomPath;
 strCurrentPath = Request.Path.ToLower();

 if (strCurrentPath.IndexOf("ID") >= 0) 
 {
  strCustomPath = "/Product10.aspx";  
  // rewrite the URL

  Context.RewritePath( strCustomPath );
 }
}

As you can see from the code above, the URL redirection is only limited to one rule. It will always redirect to a page called product10.aspx if it detects that your URL contains the ID keyword. Of course, this one will not work if you want a different querystring ID to redirect to a different page, or if you want to have different page redirection for different query string types.

To have more complex URL rewriting rules, we can use Regular Expressions for implementing different redirection techniques. Now, let's start writing some rules for your redirection.

<urlrewrites>
    <rule>
        <url>product/(.*)\.aspx</url>
        <rewrite>displayProduct.aspx?ID=$1</rewrite>
    </rule>
        <rule>
        <url>Items/Mouse/(.*)\.aspx</url>
        <rewrite>ViewItem.aspx?ID=$1</rewrite>
    </rule>

</urlrewrites>

As you can see from the first rule above, it will redirect a URL from product/(Number).aspx to displayProduct.aspx?ID=(Number). The second rule will redirect a URL if it contains Items/Mouse/(Number).aspx to ViewItem.aspx?ID=(Number). You can add as many rules as you like by just adding the XML node above.

void Application_BeginRequest(Object sender, EventArgs e)
{
    string sPath = Context.Request.Path;        
    //To overcome Postback issues, stored the real URL.

    Context.Items["VirtualURL"] = sPath;
    Regex oReg;
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(Server.MapPath("/XML/Rule.xml"));
    _oRules = xmlDoc.DocumentElement;

    foreach (XmlNode oNode in _oRules.SelectNodes("rule"))
    {
        oReg = new Regex(oNode.SelectSingleNode("url/text()").Value);
        Match oMatch = oReg.Match(sPath);

        if (oMatch.Success)
        {
            sPath = oReg.Replace(sPath, 
              oNode.SelectSingleNode("rewrite/text()").Value);
            break;
        }
    }
    Context.RewritePath(sPath);
}

The code above is self explanatory. It will search from the rules in the XML file and if it matches, then it will rewrite the path. That's all you need to do to implement URL rewriting. However, after you rewrite the URL, all your page postbacks will not work. The reason is, ASP.NET will automatically output the "action" attribute of the markup to point back to the page it is on. The problem when using URL rewriting is that the URL that the page renders is not the original URL of the request. This means that when you do a postback to the server, the URL will not be your nice clean one.

To overcome this problem, you need to add this code on every page that you want to do a postback:

protected override void Render(HtmlTextWriter writer)
{
    if (HttpContext.Current.Items["VirtualURL"] != null)
    {
        string sVirURL= HttpContext.Current.Items["VirtualURL"].ToString()
        RewriteFormHtmlTextWriter oWriter = 
               new RewriteFormHtmlTextWriter(writer,sVirURL);
        base.Render(oWriter);
    }

}

Source code for RewriteFormHtmlTextWriter

public class RewriteFormHtmlTextWriter : HtmlTextWriter
{
    private bool inForm;
    private string _formAction;

    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer):base(writer)
    {

    }
    public override void RenderBeginTag(string tagName)
    {
        if (tagName.ToString().IndexOf("form") >= 0)
        {
            base.RenderBeginTag(tagName);
        }
    }
    public RewriteFormHtmlTextWriter(System.IO.TextWriter writer, string action)
        : base(writer)
    {

        this._formAction = action;

    }
    public override void WriteAttribute(string name, string value, bool fEncode)
    {
        if (name == "action")
        {
            value = _formAction;
        }
        base.WriteAttribute(name, value, fEncode);
    }

}

That's all you need to implement a complex and fully extensible URL rewriting facility. You can create unlimited rules in your Rules.xml file and redirect to the page you want to.

Conclusion

In this article, you can see how easy it is to implement URL rewriting for your website. You can do enhancements and improve the workflow of the code above. For faster execution of your rules, you can also store the Rules.xml file as a caching object so it will save lots of time compared to opening and closing the XML file every time the rewrite happens.

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.

I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.

I love .NET programming and am doing it almost every day now.
I normally post lots of my articles here
ASP.NET Tutorial

I also host my website at ASP.NET Web Hosting

Comments and Discussions

 
QuestionCode is not working Pin
Member 1330768813-Jul-17 23:36
Member 1330768813-Jul-17 23:36 
GeneralMy vote of 4 Pin
Girish Nama4-Sep-13 19:46
Girish Nama4-Sep-13 19:46 
GeneralMy vote of 1 Pin
rahulmurari26-Apr-12 1:42
rahulmurari26-Apr-12 1:42 
GeneralContext.RewritePath(sPath); gives me Error Pin
Rizwan Bashir24-Jan-11 3:17
Rizwan Bashir24-Jan-11 3:17 
QuestionRegarding URL Rewriting Pin
hemant.tawri3-Feb-10 22:58
hemant.tawri3-Feb-10 22:58 
GeneralHi, It seems It's not working...! Pin
Member 46587445-Jun-09 23:12
Member 46587445-Jun-09 23:12 
AnswerRe: Hi, It seems It's not working...! Pin
senylity10-Jun-09 4:46
senylity10-Jun-09 4:46 
GeneralAnother easy approach.. Pin
samardeep6-Apr-09 20:17
samardeep6-Apr-09 20:17 
Hi..

This approach to have actionless form has a side effect that it disables page validations..so i tried and implemented a very simple and effective approach.. see how to rewrite url

Cheers..

programmign techniques

GeneralFor Simplest Way of writing URL Rewriting Pin
DotNetGuts24-Jul-08 10:36
DotNetGuts24-Jul-08 10:36 
GeneralNice but... Pin
zhaojicheng11-Dec-07 16:50
zhaojicheng11-Dec-07 16:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.