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();
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 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.
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.
No comments:
Post a Comment