O'Reilly logo

ASP.NET 4 24-Hour Trainer by Toi B. Wright

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 15B. URL Routing in MVC

As you learned in Lesson 8B, URL routing is a critical component of any ASP.NET MVC application. Routes are used to map incoming browser requests to their relevant controller action methods. In this lesson I show you how routing is used in an ASP.NET MVC web application, and I show you how to add a custom route.

When you create a new application using the ASP.NET MVC 2 Web Application template, a default RegisterRoutes method is created in the Global.asax page. This is the code in the default RegisterRoutes method:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",                         // Route name
        "{controller}/{action}/{id}",      // URL
        new { controller = "Home",
              action = "Index",
              id = UrlParameter.Optional}  // Defaults
    );
}

The first line of the RegisterRoutes method includes code to ignore any routes that include a file with the .axd file extension. You can use the routes.IgnoreRoute method to have routing ignore any files in your application.

An ASP.NET MVC web application uses the MapRoute method of the RouteCollection class to define new routes. The MapRoute method can include the following parameters:

  • name — This is a string representing the name of the route. This is required.

  • url — This is a string that contains the URL pattern for the route. This is required.

  • defaults — This is an object containing the default values for the route.

  • constraints — This is an object containing the constraints ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required