ASP.NET 4.0 New features – URL Routing
Hi all, In this series of posts I am going to write about ASP.NET 4.0 new features. I will try to concentrate on the important features since there are many new cool ones. At this point of writing I am using the VS.NET 2010 Ultimate Beta 2 version. So lets introduce the first feature:
URL Routing:
URL Routing is the ability to use “friendly” URL’s instead of of using the once we know so far. So instead of using the knows URL’s like:
http://www3.cet.ac.il/FieldsPage.aspx?ID=Science
http://www.google.com/search?q=vs.net+2010&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1
where we have a protocol , a host name , a directory list, a page and a query string in the format: field1=value1&field2=value2&field3=value3...
We can use a “friendlier” version like:
http://www.Developers.com/software/aspnet
These “friendly” URL’s has the following benefits:
- They are more readable ( Actually it is debatable but lets go with the flow)
- They are more SEO friendly (Search engine optimization)
The idea is to map these URL’s to a physical files by configuring your application. Up until now, this feature existed in ASP.NET MVC, now we can use it in ASP.NET 4.0. So how do we do it and where do we do it:
All we need to do is adding the routing data some where in the application , A good place to do it is in the Application_Start event so it will happen only once. Here is a sample code that demonstrate how to achieve the routing:
Adding routing to the global.asax:
protected void Application_Start(object sender, EventArgs e)
{
//Routes: An object of type RouteCollection that contains all the routes
ConfigureSiteURLRouting(System.Web.Routing.RouteTable.Routes);
}
private void ConfigureSiteURLRouting(System.Web.Routing.RouteCollection routeCollection)
{
routeCollection.MapPageRoute("RouteCategory", // A friendly name to descrive the route
"Books/{bookName}", // The url format
"~/Book.aspx"); // The actual web page to handle the request
}
Getting the url values in the destination page:
Now once I am navigating to http://localhost:1559/Books/ASPNET in my development environment I am actually running the page “book.aspx” which has the following code for getting the book parameter:
string bookName = Page.RouteData.Values["bookName"] as string;
Programmatically Generating outgoing URL’s :
Just like we can map incoming URL’s to our real pages, we can generate them for the outgoing request as well. So in order to generate a URL in the following format we can use the Page.GetRouteUrl method to perform just that.
Enjoy