Thursday, December 20, 2007

Url rewritting in some simple steps...

Introduction

Sometimes, we want that our web url will not contain any "?","&" or other kind of non readable symbols, but the question is that how to remove them from the browser's address bar, but that information is very essential for us because they are query parameters for us. So it is like we are hiding information of query string from the user by displaying some nice and readable contains, but with at server side we want our query parameters back. So that is called "URL rewriting". Don't worry it is not a difficult task.
Background

Before that, we have to have some knowledge of how the requests are processed on ASP.NET server? Remember that when any request is coming it has to pass through "Application_BeginRequest()" method in Global.asax file.

This is that access point of each and every requests those are coming to our application.So cheers it is that point where we have to work for URL rewriting.

// Write this method prototype like this,
void Application_BeginRequest(object sender, EventArgs e)
// write structure of code like this...
// First get the url of the request,
string absoluteUrl = Request.Url.AbsolutePath.ToString();
//then search for the specific page into that url of request,(means you can
//rewrite the url for some speific pages only.
if (absoluteUrl.Contains("/test/default.aspx"))
{
//now search for some redable query string parameter like you have embedded
//url link like this...http://test.com/test/default.aspx?mypageid=33
//here instade of this we can write like..
//http://test.com/test/default.aspx/MyPage33
//so you can see we have removed unreadable and ugly codes from url.
// now how to handle this and converting this back to our real information.
//find the location of last "/" character because from that "MyPage33"
//word is starting.
string pageid = absoluteUrl.Substring
(absoluteUrl.LastIndexOf('/') + 1).Trim();
//now skip first 5 characters because they are "MyPage".
pageid = pageid.Substring(6); //this will give "33".
// now generate the original Url which is required by our application.
string path = "~/test/default.aspx?mypageid=" + pageid;
//now redirect to the target page,
Response.Redirect(path);
//Bengo!!!!
//We have successfully done with Url rewriting.

No comments: