Pages

Monday, April 4, 2011

Search engine friendly URLs, also known as rewritten URLs, is a feature where a more logical and readable URL is exposed to the user. An example of such an URL is www.kindblad.com/about.

Today ASP.NET MVC supports friendly URLs out of the box through its routing feature, but the default implementation only supports hard coding of routes and pre-population of routes (using your own data source) during application startup. This is often not an ideal solution, especially when there are thousands of routes. In this post I will go through how we can change the default implementation into a dynamic one that reads the routing information from a database.

1) Let's begin by creating a Page table in our database:

Some sample data:

This table will contain a list of all the pages on our website, together with the friendly URL and the controller it maps to. For instance when a user request the URL http://www.kindblad.com/about the controller Article would be loaded.

3) Then we need a new class called PageManager that will be responsible for querying the page table in the database for a row that matches the given friendly URL, and for mapping the row to the PageItem type:

4) The next thing we need to do is to create a custom route handler. This class will be triggered by the ASP.NET MVC framework when a new request comes in to the server. This happens before the Controller has been created, so it gives us the chance to tell ASP.NET MVC that we want to load another controller than it would originally have. So create a new class named FriendlyUrlRouteHandler:

In this route handler we will take the URL. If it is not set, we will set it to the default which is home. Then we will query the Page table for a row that matches the friendly URL. Further we will change the RouteData.Values["controller"] to the controller we want to load. After ASP.NET MVC has executed the code it will load the controller that we defined in the RouteData.Values["controller"].

5) And the last thing we need to do is to tell AS.NET MVC that we want to use our own route handler. So modify the RegisterRoutes method in the Global.asax to the following: