We have already discussed basic about ASP.NET MVC routing here. So in this post we are going to discuss about more on routing with examples.

What is Routing?

Routing is set of rules/pattern matching system that monitor the incoming request from the broswer and set matched location to process further.

The Routing engine uses the virtual route table which helps to find the matching pattern for the incoming request (URL) from the browser.

The route has the following 3 segments:

Controller : define the controller{controller}

Action : define the action{action}

Parameter : define the parameter{id}

Let me explain the above segments with examples.

Example 1: With No paramerter

We can find Route configuration inside App_Start (Folder) –> RouteConfig.cs

Controller:

public ActionResult Index()

{

return View();

}

RouteConfig.cs:

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

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

routes.MapRoute(

name: “Default”,

url: “api/{controller}/{action}/{id}”,

defaults: new { id = UrlParameter.Optional });

}

}

We can also state that the default or optional values are provided for all the three segments. The Controller has a default value of “Home”, the action has a default value of “Index” and id is an optional value.

Let us assume www.dotnet-helpers/Home/Index/ has been requested from the browser. Then the default route maps this URL shown below.

controller : Home

action : Index

Example 2: With Parameter

Controller:

public ActionResult Index()

{

return View();

}

public ActionResult Index1(int id)

{

return View();

}

The default route will handle the below requests and redirect to the matched controller and action method ( ie., index () and index1 (int id)).

http://localhost:50287/dotnet_helpers/index

http://localhost:50287/dotnet_helpers/index1/1

Let us assume www.dotnet-helpers/Home/Index/500 has been requested from the browser. Then the default route maps URL shown below.

controller : Home

action : Index

id : 3