Thursday, June 5, 2008

URL Rewriting

It has become important for websites to provide User friendly URL's to their users and this can be done effectively using Visual web developer.
Today I will tell you about one of the ways of doing it .

We will start a new website and add an App_Code folder to your solution .
App_Code folder is a special folder which contains the code which is executed at the start of our application .
Add a class file to the App_Code folder,I have named it Urlrewitw.cs
Write the following code in this file :

public class urlrewrite:IHttpModule//This class implements IHttpModule which generates two functions called Dispose and Init

{
#region IHttpModule Members

public void Dispose()//the code in this function executes whenever the application disposes
{
// We dont need to write any code in this function
}

public void Init(HttpApplication context)//this code is executed at the start of application
{
context.BeginRequest += new EventHandler(context_BeginRequest);
//We add an event handler which calls the begin_request function at the start of application
}

void context_BeginRequest(object sender, EventArgs e)//Write the url rewriting code here
{
HttpApplication app;
app = (HttpApplication)sender;
if (app.Request.RawUrl.Contains("Default4.aspx"))
{
app.Context.RewritePath("Default3.aspx", "", "itemid=2" + "&name=anand");
//if Default4.aspx is requested then call the page Default3.aspx with two QueryString Parameters itemid and name: Default3.aspx?itemid=2&name=anand
}

}

#endregion
}

Last Thing to be done is to Tweak the Web.config file
In System.Web add this code-snippet
(httpModules)
(add name="urlrewrite" type="urlrewrite"/)
(/httpModules)
Use < > brackets instead of ( )

Isnt it easy ,so go and try this code in your application.....

No comments: