WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 61 users


WorldofASP.NET >> ASP.NET >> Applications

URL Rewriting with ASP.NET 2.0

How to implement URL Rewriting and Improve your SEO rankings.
Published Date : 25 Aug 2007
Author : James Douglas
Language : VB.NET,C#
Platform : Wins
Technology : Visual Studio,ASP.NET
Views : 72351
Rating : (1 votes so far)



Introduction

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

Most Search Engines will ignore those dynamic URL such as the one ended with querystring
e.g http://www.worldofasp.net/displayproduct.aspx?ID=10
Therefore if you like to have more hits and  traffic from search engine, consider of rewriting all those querystring url into normal URL.

If you rewrite the URL above, you can actually rewrite it into 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 robot will think that your dynamic page is a normal page and therefore it will crawl your page and your page will have a better search results.
If you check all the page in Worldofasp.net or CodeProject.com, you can see that the web developer is using URL rewriting techniques.

Main

Microsoft .NET Framework 2.0 come with 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 copy and paste the code below to your global.asax file.

void Application_BeginRequest(Object sender, EventArgs e) 
{
String strCurrentPath;
String strCustomPath;
strCurrentPath = Request.Path.ToLower();<BR>if (strCurrentPath.IndexOf("ID") >= 0) 
{
strCustomPath = "/Product10.aspx";// rewrite the URLContext.RewritePath( strCustomPath );
}
}
As you can see from the code above, the URL Redirection is only limited to one rules. It will always redirect to one page called product10.aspx if it detects that your URL contains ID keyword.
Of course this one will not work if you want different Query String ID to redirect to different page or if you want to have different page redirection for different query string type.

To have a more complex URL Rewriting Rules, we can use Regular Expressions for implementing different redirection techniques.

Now, lets 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 rules above, It will redirect the URL from product/(Number).aspx into displayProduct.aspx?ID=(Number).
Second rules will redirect the URL if it Contains Items/Mouse/(Number).aspx into 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 XML file and if it match, then it will rewrite the path.
Thats 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 because, ASP.NET will automatically by default 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 postbacks.

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. You can create unlimited rules into your Rules.xml file and redirect to the page you want.

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 stores the Rules.xml files as Caching objects so it will save lots of time compare to open and close the xml files everytime the rewrite happens.




Other Related and Popular Articles :

Sending Email in ASP.NET 2.0
Send email in ASP.NET 2.0 Framework with or without SMTP Authentication

Building a Photo Tagging Application using ASP.NET 2.0, LINQ, and Atlas
In this article, I will examines how to build a photo tagging application using ASP.NET 2.0, LINQ and Atlas framework.

Using LINQ to XML (and how to build a custom RSS Feed Reader with it)
In this article, Scott examines how to work with LINQ using XML. He also demonstrates how to build a custom RSS Feed Reader using these technologies.

Creating Contact Us Form easily using ASP.NET and SMTP
This article explain how to create a simple contact us form by using ASP.NET and System.Net.Mail to send email to the website owner

Build a DotNetNuke FileManager in ASP.NET
Tutorial and Code Sample on building a DotNetNuke FileManager in ASP.NET


Author Profile : James Douglas

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.

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

#Thanks for the article, i have a few issues though
06 Dec 2009 18:19 by : Egli

Hi thanks for this article its awesome i rather use this then the intelligencia url rewrite thats around...

ive tested it on my local and it works like just fine.. the weird thing is once i put this on my staging or production server it does not redirect... have any of you guys experieced this before i cant imagine a reason why its not working...

thanks in advance

Egli

#URGENT :- Page loaded without CSS and IMAGES after URL rewriting
21 Aug 2009 2:34 by : BugmeNot

hi

Please help me out
im not able to get any images and CSS on the page after url rewriting with your technique.

though content is available but with all white background and no images

plz help
its urgent

#hi I need a help in Rewritting Url
29 May 2009 6:55 by : Sonali

hi
i m using vs2008 with c# and i want to rewrite my url that they are crawl by search engine. so sir plz send me sample code in c#
thanx

#Hi - need your help - URL Rewriting
15 Oct 2007 9:49 by : srini

Hi im new to URL rewriting. I tried most coding, but couldnt find solution for URL rewriting. Can u help me by sending a sample simple url rewriting code in c# asp.net. That would be great help for me.

Thakns in advance,
srini

Leave New Comments


Article Content copyright by James Douglas
Everything else Copyright © by WorldofASP.NET 2010

Category
.NET 3.5
AJAX and ATLAS
ASP.NET
C# Programming
Classic ASP
Enterprise Systems
General .NET
VB.NET Programming
Announcements
Earn Cash by writing an article or review
For more info Click here







Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2010 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | ASP Hosting | ASP.NET Hosting | Phone Card | Calling Card |Stock Investing