MVC 3 Routing Example

Published on Oct 17, 2011 by Jamie Munro

Below is an excerpt of a chapter from my new book: 20 Recipes for Programming MVC 3.

In todayís heavily fought battles for search engine supremacy, itís quite difficult to winthe race with a website address that looks like:
http://www.example.com/books/details?id=4.

Using routes, the website can look like:
http://www.example.com/20-recipes-for-mvc3

which provides much more context, both to the user and the search engine.


Routing is set up in MVC through the Web.config and the Global.asax.cs file. In the Web.config, the System.Web.Routing assembly is included and then used in the Global.asax.cs file to create a default routing mechanism for all controllers and actions in them. Hence when a BooksController is added, it can be accessed via the /Books URL without an extension, like in ASP.NET websites.

The following recipe will demonstrate several different useful techniques for setting up routes. The first route will allow the website to link directly to the title of the book. For example, if there is a book called 20 Recipes for Programming MVC 3, it could be accessed directly by visiting http://localhost/20 Recipes for Programming MVC 3, whereas the current solution would require a more complicated URL like http://localhost/Books/Details?id=1.

To begin creating this route, open the Global.asax.cs file in the MVC project. A default route is created in the RegisterRoutes() function which is called from the Application_Start() function when the website first loads. The example below contains an updated RegisterRoutes function with the new route that is added with the MapRoute function:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MvcApplication4.Models;
using System.Data.Entity;
using System.Globalization;
using System.Threading;
namespace MvcApplication4
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(
GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"BookName", // Route name
"{Keyword}", // URL with parameters
new { controller = "Books", action = "Index",
id = UrlParameter.Optional },
new { Keyword = "\\w+" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
// URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
}
protected void Application_Start()
{
Database.SetInitializer<BookDBContext>(
new BookInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
protected void Application_AcquireRequestState(
object sender, EventArgs e)
{
if (HttpContext.Current.Session != null)
{
CultureInfo ci =
(CultureInfo)this.Session["CurrentLanguage"];
if (ci == null)
{
ci = new CultureInfo("en");
this.Session["CurrentLanguage"] = ci;
}
Thread.CurrentThread.CurrentUICulture = ci;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(ci.Name);
}
}
}
}


In the above example, the MapRoute function accepts four parameters:

1. The route name; in this case BookName.

2. The URL with any parameters; in this case, {Keyword}, which is a variable that will be used later.

3. The parameter defaults for the controller, action, and any additional variables; in this case, the default controller is Books and the default action is Index.

4. The constraints (e.g., variables) for the URL; in this case, the previously mentioned Keyword variable is passed to the index action in the BooksController.

The above route will take advantage of the previous change to the BooksController when a keyword is being searched: that if only one result is returned, the user will be redirected to the details page. This provides the user with the ability to enter a book title or keyword in the URL after the domain name. If only one result is returned, theuser will see that book; otherwise, the user will see a search result with their keyword.

In the next example, a new route will be created that is a bit more complicated. It willextend the RouteBase class, allowing for a much more complicated route. Instead ofsearching for the book by the title at the end of the domain name, a subdomain will beused instead. For example, http://mvc3book.localhost/ will return the book details forthe aforementioned book 20 Recipes for Programming MVC 3.

Get the book for more!

Tags: SEO (Search Engine Optimization) | ASP.NET | mvc 3

Related Posts

blog comments powered by Disqus