Friday, July 29, 2011

Routing in Asp.Net 4

Routing basically is a way of making simple SEO (Search Engine Optimization) friendly easy to remember URLs, with routing your request is not mapped to physical files like www.mysite.com/About.aspx.
Routing is not new in Asp.Net 4 its first introduced in Asp.Net 3.5 SP1.

Why we need routing
Problem 1.
If you see a URL like
www.mysite.com/Product/ProductCategory.aspx?category=134324
when next time you want to access this page you will definitely open some other random category.

Problem 2.
If your URL is
www.mysite.com/Product/ProductCategory.aspx?category=134324
by watching this i knew this page is in some Product folder having ProductCategory.aspx page which hacker love to know.

Problem 3.
If your page is now move to some other hierarchy or its renamed and user request that some page he will not find that page.

How to solve these issues
Problem 1.
If you see a URL like
www.mysite.com/Category/laptops
you will definitely remember and will find it next time you try to visit it. This solves our Problem 1.

Problem 2.
If you see a URL like
www.mysite.com/Category/laptops
Nobody knows what is the physical hierarchy by watching this URL. This solves our Problem 2.


Problem 3.
If you see a URL like
www.mysite.com/Category/laptops
Because it is not mapped to a physical page, moving or changing its name doesn't affect the user. This solves our Problem 3.

Demo

1. We start from File -- New Project then choose Asp.Net Web Application and select .Net Framework 4 and click Ok.

2. Define Route setting in Global.asax file.

a. First we have to add a System.Web.Routing namespace, which provide all the classes used in URL routing

b. Make a method for RegisterRoutes that accepts a RouteCollection parameter and define route for our request. RouteTable.Routes.MapPageRoute function have 5 overloaded methods, we are using the first and the basic one which accepts three paramters.


private void RegisterRoutes(RouteCollection collection)
{            
RouteTable.Routes.MapPageRoute("ProductRoute",  //Name of route
"Product/{Name}",                                                   //How request map the url ex Product/laptops
"~/Product.aspx");                                                   //Physical page that handles these requests
}


c. Call RegisterRoutes in Application_Start event and pass RouteTable.Routes as object in it. RouteTable.Routes get a collection of objects that derive from the System.Web.Routing.RouteBase class.

void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}


Global.asax work complete.


3. On Default.aspx page make a link to redirect to Product page.
<a href="/Product/All">Show all Products</a>

4. Add a new Product page on the root, In Product page we will print the product categories name in a label as a heading and some text description. 
Just for showing demo i have made 3 hyperlinks of product categories and after selecting them we will display its name in heading and some text description for it.

<asp:HyperLink ID="Hyplaptops" runat="server" NavigateUrl='<%$RouteUrl:Name=Laptops %>' Text="Laptops"></asp:HyperLink><br />
<asp:HyperLink ID="HypMobile" runat="server" NavigateUrl='<%$RouteUrl:Name=Mobile %>' Text="Mobile"></asp:HyperLink><br />
<asp:HyperLink ID="HypTablets" runat="server" NavigateUrl='<%$RouteUrl:Name=Tablets %>' Text="Tablets"></asp:HyperLink><br />
<asp:Label ID="lblProductTitle" runat="server" Font-Size="X-Large"><%: RouteData.Values["Name"] %></asp:Label><br />
<asp:Label ID="ProductInfo" runat="server" ></asp:Label>


In code behind of Product page, set the label text according to route conditions


if (RouteData.Values["Name"].ToString().Equals("All"))
            {
                ProductInfo.Text = "Show All Products";
            }
            else if (RouteData.Values["Name"].ToString().Equals("Laptops"))
            {
                ProductInfo.Text = "Show All Laptops";
            }
            else if (RouteData.Values["Name"].ToString().Equals("Mobile"))
            {
                ProductInfo.Text = "Show All MobilePhones";
            }
            else
            {
                ProductInfo.Text = "Show All Tablets";
            }


In just four easy steps we configure routing in Asp.Net 4. 
Now run Default.aspx page and click Show All Products hyperlink and you can see the clean URL showing Product/All means show all Product categories. 
Now click on Laptops hyperlink and URL will change to Product/Laptops.