.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> ASP.NET Controls >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

URL Rewriting in ASP.NET

Posted By:Athira Sreejith       Posted Date: December 31, 2008    Points: 10    Category: ASP.NET Controls    URL: http://www.dotnetspark.com  
 

Through this code 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. 

Global.aspx:

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

if (sCurrentPath.IndexOf("ID") >= 0) 
{
sCustomPath = "/addproduct.aspx"; 
// rewrite the URL
Context.RewritePath( sCustomPath );
}
}

void Application_BeginRequest(Object sender, EventArgs e)
{
string strPath = Context.Request.Path; 
Context.Items["VirtualURL"] = strPath;
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);
}



some rules for your Redirection. 


product/(.*)\.aspx
displayProduct.aspx?ID=$1


Items/Mouse/(.*)\.aspx
ViewItem.aspx?ID=$1





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);
}

}


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend