Asp.Net MVC Routing

Here we will learn how to use URL routing in asp.net mvc with example and how to configure URL patterns using asp.net mvc routing with example.

Asp.Net MVC Routing Overview

The route is just a URL pattern that is mapped to a handler. In ASP.NET MVC routing is just a pattern matching system whenever the user sends a request to an MVC application, and if it is the first request, the first thing is to fill the route table.

What is Route Table in Asp.Net MVC?

The Route Table is a class that stores the URL routes for your application.

 

Depending upon the URL request by the user, using UrlRoutingModule you can find URL in the Route table to create RouteData object. If UrlRoutingModule finds a correct match, it goes to create RequestContext, and then it forwards the request to the appropriate MVCHandler. Once MVCHandler receives a request, it invokes the execute method on the Controller.

 

The Execute() method gets the Action from the RouteData based on the requested URL. The MVC Controller will call Controller ActionInvoker that creates a list of parameters coming with URL. The parameter list will be passed to the Controller Action method. It calls the InvokeAction method to execute the action. Finally, send a response to the browser.

Where is routing located in MVC application?

In your application, there is an App_Start folder inside that you will see RouteConfig.cs. It will contain all routing configuration details.

How to configure route in MVC?

Following is the default route provided by the Asp.Net MVC application.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

 

namespace Tutorial3

{

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

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

 

routes.MapRoute(

name: "Default",

url: "{controller}/{action}/{id}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

}

}

}

Here we can set your startup page for your application. In place of home controller, you can add your own controller name thatever you have created, and related action in the Index. If you are passing parameters, it will come in { id }. We need to change the following code line for custom routing implementation.

 

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

In case If you want to increase or pass multiple parameters then you can do it like as shown below.

 

routes.MapRoute(

            "Default",     // Route name

            "{controller}/{action}/{Userid}/{requestID}",  // URL with parameters

            new { controller = "Home", action = "Index", Userid = "", requestID = "" } );

This way we can set url pattern for our asp.net mvc application using routing configuration.