According to MSDN ASP.Net routing is
ASP.NET routing enables you to use URLs that do not have to map to specific files in a Web site.
What does that mean? Simple you can have a url like below in your application.
http://localhost:51174/Day/6/10/2010
Normally the url comes with a .aspx extension such as Default.aspx.This gives the user a clear understanding of which file will process the request.But the above URL doesn’t tell anything about the file which is going to process it.Also there is no file called 2010 without any extension.But we know without a request processor the ASP.Net cannot return anything back to the client. So how this is handled internally?
Here comes the Routing feature of ASP.Net.We can easily specify the URL format and the corresponding file which is going to handle the request as follows in the Global.asax.cs file.
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("",
"Day/{Day}/{Month}/{Year}",
"~/Default.aspx");
}
Very simple.It defines the pattern which routes to the default.aspx.Now only thing remaining is how the Default.aspx.cs is going to handle the data.ie how it process the particular request considering the parameters.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.RouteData != null &
this.RouteData.Values.ContainsKey("Day") &
this.RouteData.Values.ContainsKey("Month") &
this.RouteData.Values.ContainsKey("Year"))
{
int day = Convert.ToInt32(this.RouteData.Values["Day"]);
int month = Convert.ToInt32(this.RouteData.Values["Month"]);
int year = Convert.ToInt32(this.RouteData.Values["Year"]);
DateTime dt = new DateTime(year, month, day);
Response.Write(dt.DayOfWeek.ToString());
}
else
{
Response.Redirect(string.Format("~/Day/{0}/{1}/{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year));
}
}
}
Self explanatory…Get the data through the property RouteData which belongs to the Page class.The sample uploaded here is to show the Day of the week if you request with the day,month and year as integers.ie the request http://localhost:51174/Day/6/10/2010 will give Wednesday.
There are lot more things you can achieve using the Route feature.Refer the MSDN article.http://msdn.microsoft.com/en-us/library/cc668201.aspx
Don’t think that this was not possible in earlier versions of ASP.Net.It was possible using HttpModules and the common name was URL rewriting.Refer the below links to get more information.
http://www.dotnetfunda.com/articles/article550-url-rewriting-with-http-module-in-aspnet.aspx
http://msdn.microsoft.com/en-us/library/ms972974.aspx
I am seriously looking for the differences between the old HttpModule implementation and this new Route feature except for the ease of use of Route.
No comments:
Post a Comment