MVC Routing

What is Routing?
Routing simplifies MVC url. Routing helps us to create user friendly url and those urls can easily maps with technical controller names and action names.
How to simplify the url?
Some developers maintains some coding standard i.e. naming standard like using prefix word Cls before class name e.g. ClsHomeController. Also some developers put Sub as prefix for subroutine e.g. SubGotoHome.
R-1
If you have such type of naming convention then it is very difficult to end user to write url because end user have to write

http://localhost:portno/ClsHome/SubGotoHome

The end users are non technical person and they will not understand what is the meaning of Cls and Sub. So these types of url is definitely not user friendly.
Routing helps us to simplify these type of url and avoid the confusions of end users.
If we remove Cls and Sub prefix from our controller name and action name then the code looks like follows:
R2
Now the url is more simple and user friendly. User will just type the Controller name and Action name as follows:

http://localhost:portname/Home/GotoHome

Now we want to make our end users life easier. The end user will just type the site name. As soon as he/she will type the site name and Controller name of then will automatic invoke the action i.e. end user will just type “site name”/”controller name” it will automatic invoke the action. He/she doesn’t need to type the action name.
In order to do that we’ll go to Solution Explorer -> Expand “App_Folder”-> Open “RouteConfig.cs” as follows:
R3
As we open the RouteConfig.cs we’ll see following code inside this class:
R4
Inside above code we’ve a method named RegisterRoutes that passes RouteCollection as the parameter.
Inside the method adds different routing patterns inside the RouteCollection using MapRoute method of RouteCollection.
MapRoute takes three important values
01. Name: It is the key name. Every collection has a key name. In this case the key name is “Default”
02. url: The routing pattern. In this case the pattern is {controller}/{action}/{id}
03. defaults: Set the default value of the pattern. In this case the default value is controller = “Home”,
action = “index”, id = “UrlParameter.Optional
Now if we want to add another route we will have to do as follows:

routes.MapRoute
(
	name: “Home”,
	url: “Home”,
	defaults: new {controller = “Home”, action = “GotoHome”, id=UrlParameter.Optional }
)

So when if anybody types “site name”/ “controller name” it will automatically invoke the action i.e. “site name” / “Home” then it will automatically invoke the action “GotoHome”
Now run the application and type http://sitename/Home it will show the output follows:
R5
Now if we want to reduce more pain of end user i.e. end user will only type the site name and it will automatically route to “GotoHome” action of “Home” controller then we will define another route and add it with RouteCollection using MapRoute as follows:

routes.MapRoute
(
	name: “Home1”,
	url: “”,
	defaults: new {controller = “Home”, action = “GotoHome”, id=UrlParameter.Optional }
)

Now if the end user type only site name i.e. http://sitename then it will automatically route to the “GotoHome” action of “Home” controller as follows:
R6
So we can say that routing is nothing but it create user friendly url and map those user friendly url with controller and action.


Tips:

@. Key name must be unique i.e. one key name can’t be used for two routing otherwise it will return error that duplicate key name.
@. Don’t remove the default route configuration that already exists when we first opened the RouteConfig.cs file because incase if any of our custom route doesn’t work properly or none of the custom url match then our application will route by using default route configuration.
Also never move the default route setting code as the start of the route setting code. If you do this then by default the default route will get invoked and other route will bypass. So until match the default route pattern no page will displayed and give us an error message. So in order to avoid this place default route setting at the end of all other custom route setting as follows:

public static void RegisterRoutes (RouteCollection routes)
{
	routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
	routes.MapRoute(
		name: “Home”,
		url: “Home”,
		defaults: new {controller = “Home”, action = “GotoHome”, id=UrlParameter.Optional };
	);
	routes.MapRoute(
		name: “Home1”,
		url: “”,
		defaults: new {controller = “Home”, action = “GotoHome”, id=UrlParameter.Optional };
	);
	routes.MapRoute(
		name: “Default”,
		url: “{controller}/{action}/{id}”,
		defaults: new {controller = “Home”, action = “Index”, id=UrlParameter.Optional };
	);
}

@. RouteCollection has another method IgnoreRoute that used inside RegisterRoutes method inside RouteConfig.cs. Sometimes we don’t want end user to access .xml files, .config files, .axd files etc. In order to protect those files from end user we uses IgnoreRoute method. Here by default set .axd file to ignore as follows:

routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

In above code resource is any resource that’s extension is .axd type will ignored
If we want to ignore .xml file then we’ll add following code

routes.IgnoreRoute(“{resource}.xml”);

So any file that contains .xml extension will ignore during browsing.
If we want to ignore .xml file then we’ll add following code

routes.IgnoreRoute(“{resource}.config”);

So any file that contains .config extension will ignore during browsing.
So the final word is IgnoreRoute uses to ignore any type of routes during browsing so the end user will not be able to browse that route.
@. If any one want to set any page as start page then he/she have to define a new route with url= “” inside RegisterRoute method of RouteConfig.cs as follows:

routes.MapRoute(
		name: “Home1”,
		url: “”,
		defaults: new {controller = “Home”, action = “GotoHome”, id=UrlParameter.Optional };
	);

According to above code when the user will browse the application by only giving site name it will first call the Home Controller then invoke the GotoHome action of Home controller.

Md. Mojammel Haque
Currently working as Lead Team (Application Architecture) at Raven Systems Ltd.

Passion for software development especially agile practices such as TDD & BDD with in depth knowledge of OOP, DDD, CQRS, ES, GoF, SOLID and PoEAA.

Over 6 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time.

Also experience in non Microsoft .NET technologies such as Dapper.Net, Subversion, Structure Map & AngularJs.

601 Total Views 2 Views Today
First Application in ASP.NET MVC
Developer Testing

Comments (2)

  1. This is the best explanation about mvc routing I ever was seen. Thanks a lot, Mr. Mojam for written this type of blog for beginner level programmer likes us.

Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>