Create custom routes in MVC

Routes are core components of mvc application, they determines how the URLs are mapped to the controller and controller actions.

When you define a route in Global.asax file, you need to specify the expected layout of any matching URL, such as {controller}, {action} in the default route, default values, constraints and data tokens.

Here is an example of the default route,

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

The first segment of the URL is mapped to the controller name, the second segment of the URL is mapped to the controller action, and the final segment of the URL is mapped to a parameter named Id.

Now let’s create a custom route and place it before the default route, There are two segments in the URL, the first is a constant value “archive”, the second is a string value for “entryDate”, the URL is mapped to Blog controller and Details method.

            routes.MapRoute(

                 "Archive",   

                 "Archive/{entryDate}",  

                 new { controller = "Archive", action = "Details"}

             );

Further more, we create a constraint for this custom route, the constraint is defined by using regular expression, so here it restricts the second segment of the URL to be a formatted string “dd-dd-dddd” with digits.

            routes.MapRoute(

                 "Archive", // Name  

                 "Archive/{entryDate}", // URL

                 new { controller = "Blog", action = "Details" }, // Defaults

                 new { entryDate = @"\d{2}-\d{2}-\d{4}" } // Constraints

             );

There is another type of route – Catch all route, with a “*” in front of the segment. A catchall route is a route that can contain any number of segments. For example, “Product/{*values}” the catchall route will match:

/Product/a

/Product/a/b

/Product/a/b/c

routes.MapRoute(

   "CatchIt", // Name

   "Product/{*values}",  // URL

   new { controller = "Product", action = "Index" } // Defaults

);

Be careful with this type of routes, because it matches the first segment and ignore the rest segments of the URL, we normally register this route after our default route.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s