Tuesday, April 12, 2011

Custom Routing in MVC

In MVC, by default, out of the box routing pattern is {controller}/{action}/{id} where id is optional as defined in the Global.asax.cs:

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


However, this will not always meet your needs.  In such case, you can create custom routes.  For instance, let's say it is a requirement that the "HR (Human Resource)"  department of your company should have their own unique URL in a pattern like this: "Hr/PersonalProfile/Display/1234".  Custom route can be utilized to make this work:

            routes.MapRoute
                (
                    "Hr"// The name must be unique in a route table
                    "Hr/PersonalProfile/{action}/{id}"// URL with parameters
                    new {controller = "PersonalProfile", action = "Display", id = UrlParameter.Optional} // Parameter defaults                );

Now you can display a personal profile using this URL: http://{yourdomian}/Hr/PersonalProfile/Display/1234

One very important thing to note is that MVC tries to find matching route in the order of the routes registration.

In our example, the custom route "Hr" must be registered before the default route is.  Otherwise, when the site is accessed with the URL "http://{yourdomian}/Hr/PersonalProfile/Display/1234", it matches the default route and it will try to look for a controller named "Hr" which doesn't exist.  This, of course, results in an error as below:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Hr/PersonalProfile/Display

Phil Haack created a very useful tool for debugging MVC routing: route debugger and you can get it through NuGet package management tool.  Just type in the following command in Package Manager Console:
PM> install-package routedebugger

If you're not familiar with NuGet, read about it here.  And download it from here.



About Cullen

My photo
Christian, Father, Software Developer/Architect who enjoys technology and using it to make people's lives easier!

Followers