Click here to Skip to main content
16,017,650 members
Articles / Web Development / ASP.NET

Custom Routes for MVC Application

Rate me:
Please Sign up or sign in to vote.
4.63/5 (8 votes)
13 Dec 2011CPOL4 min read 110.9K   1.7K   34   5
Provides details about ASP.NET MVC Routing architecture and customize structure of the URLs of your ASP.NET MVC applications.

Introduction

When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.

In this article, we will show how to Create Custom Routes, Debugging Routes and Router Constraints.

Using Default Route

You can configure Route into the Global.aspx's Application Start Event. When you are creating an MVC application, it will already define Default route. Default route can be configured using the following code:

C#
routes.MapRoute(
"Default",  //Route Name
 "{controller}/{action}/{id}" //Url With Parameters
, new { controller = "Home", action = "Index", id = ""} // Parameter Defaults
);

Custom Routes

It is possible to develop an MVC application without creating a Custom Route. But sometimes, there is a situation to change the pattern of URL in which it makes sense to create Custom Routes.

Now, we take a simple example of the custom routes. Imagine that you want to create a blog application and you want to route a request look like: /Archive/12-25-2010.

The first step is to create an empty MVC application. And Add Controller File named BlogController.cs and Add Actions named Archive and insert that code will look like below:

C#
public class BlogController : Controller
    {
        //
        // GET: /Blog/

        public string Archive(DateTime? entryDate)
        {
            return "You wants Blog Entry on Date:=" + entryDate.ToString();
        }


        public ActionResult Insert()
        {
            ViewData["Message"] = "Call From the Insert Action When Get Http Occurs";
            return View();
        }
    }

Now go the Global.asax file and add the following code into the Register Routes method.

C#
//Simple Custom Route with out any Constraints
routes.MapRoute(
                "BlogWithoutConstraint",
                "Archive/{entrydate}",
                new { Controller = "Blog", action = "Archive", });

This code used to add Custom routes and it will match the URL like, Archive/12-25-2010.

Route Constraints

When you create a Custom Route, you can also include route constraints. These constraints are used to restrict the requests to match routes. There are three basic types of constraints:

  1. Regular Expression Constraints
  2. HttpMethod Constraints
  3. CatchAll Values

Regular Expression Constraints

You can use regular expression constraints to check the pattern of the Route and prevent invalid requests. Regular expression is used to check any pattern like Currency, Date, time, etc.

In the Above BlogArchive Example, Url likes Archive/12-25-2010 and Archive/mybirthday.

It will allow. Now we have to prevent parameter which is not a date. So it is possible using regular expression constraints. For that, add the following code into Global.aspx file Register Route method.

C#
//Custom Route With Regular Expression Constraints
            routes.MapRoute(
                "Blog",
                "Archive/{entrydate}",
                new { Controller = "Blog", action = "Archive" }, 
        new { entryDate = @"\d{2}-\d{2}-\d{4}" });

The above code matches the entry date must match pattern of two decimals followed by dash followed by two decimals followed by dash followed by four decimals.

HTTP Method Constraints

You can match route with any type of the HTTP operation like POST, GET, etc. you want to prevent user to access particular URL when GET operation occurs but not POST operation occurs. You can also used AcceptVerbs instead of HttpMethod constraints.

For example, BlogArchive example inserts Action only executes when HTTP GET Operation performs. For that, you have to add the following code into Global.asax file Register Route method.

C#
//Custom Route With HttpMethod Constraint
            routes.MapRoute(
                "HttpMethodConstraintRoute",
                "Blog/Insert",
                new { Controller = "Blog", action = "Insert" }, 
        new { method = new HttpMethodConstraint("GET") });

Catch All Routes

Generally, your URL must match with number of segments, but you want to match your URL, regardless of the number of the segments for that, we have to create Catch-All Parameter. Now take a simple example of the Catch All Routes for that add one controller named CatchAllController and add the following code into the controller.

C#
public class CatchAllController : Controller
{
        //
        // GET: /Sort/
       public string Index(string AllValues)
       {
          string[] PassedValue = AllValues.Split('/');
          return "You are Passing Values:" + String.Join(",", PassedValue);
       }
}

Now to catch all parameters, add the following code into the global.asax file’s register route method.

C#
//Custom Route Catch-All  Routes
      routes.MapRoute(
           "CatchAllRoute",
            "CatchAll/{*AllValues}",
            new { Controller = "CatchAll", action = "Index" });

Now it will match the following URL like, CatchAll/index/1/2/3/4/5/6/7 and CatchAll/a/b/c/d/e/f/g/h/.

A catch-all parameter must appear as the last parameter. Think of a catch-all parameter as a parameter array.

Debugging Routes

After creating Custom Routes, you have to check whether your routes work perfectly with your given URL or not. For that, you have to debug your routes. To Debug Routes, you have to download one DLL from the http://code.haacked.com/mvc-1.0/RouteDebug-Binary.zip and add a reference into your MVC Application.

Now debug route you have to write the following line of the code into the Global.asax Application Start Event.

C#
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);

And run your application. You will see the below screen in your browser:

RouteTesting.JPG

You can see all the custom routes into All Routes Table and it will show that your browser URL matches with which Routes. If it will match any Routes, it will show true into the Match Current Request Routes, otherwise it will show false. You can check with another URL, for that you have to write URL into the Address Bar.

Now write URL like, CatchAll/1/2/3/4/5/6/. It will match with the Catchall CustomRoutes.

In this way, you can check with other Routes too. It is possible that your URL matches with more than one Route, at that time the first match Routes Executes.

Conclusion

The goal of this article is to demonstrate the flexibility of the routing system provided by ASP.NET MVC. Hope this helps!

History

  • 13th December, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I have been working as a Software Engineer on Microsoft .NET Technology.I have developed several web/desktop application build on .NET technology .My point of interest is Web Development,Desktop Development,Ajax,Json,Jquey,XML etc.I have completed Master of Computer Application in May-2011.I'm not happy unless I'm learning something new.

Comments and Discussions

 
GeneralThank you baba Pin
Member 1109139518-Feb-15 2:38
Member 1109139518-Feb-15 2:38 
QuestionLooks a lot like Phil Haack's code... Pin
Robb Sadler8-Apr-13 4:20
Robb Sadler8-Apr-13 4:20 
AnswerRe: Looks a lot like Phil Haack's code... Pin
Snesh Prajapati15-Apr-14 20:37
professionalSnesh Prajapati15-Apr-14 20:37 
GeneralMy vote of 4 Pin
AbdullaMohammad20-Dec-11 0:51
AbdullaMohammad20-Dec-11 0:51 
GeneralRe: My vote of 4 Pin
Jigar Bagadai21-Dec-11 1:34
Jigar Bagadai21-Dec-11 1:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.