ASP.NET MVC Routing Overview (C#) (2024)

  • Article

by Stephen Walther

In this tutorial, Stephen Walther shows how the ASP.NET MVC framework maps browser requests to controller actions.

In this tutorial, you are introduced to an important feature of every ASP.NET MVC application called ASP.NET Routing. The ASP.NET Routing module is responsible for mapping incoming requests to particular MVC controller actions. By the end of this tutorial, you will understand how the standard route table maps requests to controller actions.

Using the Default Route Table

When you create a new ASP.NET MVC application, the application is already configured to use ASP.NET Routing. ASP.NET Routing is setup in two places.

First, ASP.NET Routing is enabled in your application's Web configuration file (Web.config file). There are four sections in the configuration file that are relevant to routing: the system.web.httpModules section, the system.web.httpHandlers section, the system.webserver.modules section, and the system.webserver.handlers section. Be careful not to delete these sections because without these sections routing will no longer work.

Second, and more importantly, a route table is created in the application's Global.asax file. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event.

The file in Listing 1 contains the default Global.asax file for an ASP.NET MVC application.

Listing 1 - Global.asax.cs

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;namespace MvcApplication1{ // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit https://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { RegisterRoutes(RouteTable.Routes); } }}

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id.

Imagine that you enter the following URL into your web browser's address bar:

/Home/Index/3

The Default route maps this URL to the following parameters:

  • controller = Home

  • action = Index

  • id = 3

When you request the URL /Home/Index/3, the following code is executed:

HomeController.Index(3)

The Default route includes defaults for all three parameters. If you don't supply a controller, then the controller parameter defaults to the value Home. If you don't supply an action, the action parameter defaults to the value Index. Finally, if you don't supply an id, the id parameter defaults to an empty string.

Let's look at a few examples of how the Default route maps URLs to controller actions. Imagine that you enter the following URL into your browser address bar:

/Home

Because of the Default route parameter defaults, entering this URL will cause the Index() method of the HomeController class in Listing 2 to be called.

Listing 2 - HomeController.cs

using System.Web.Mvc;namespace MvcApplication1.Controllers{ [HandleError] public class HomeController : Controller { public ActionResult Index(string id) { return View(); } }}

In Listing 2, the HomeController class includes a method named Index() that accepts a single parameter named Id. The URL /Home causes the Index() method to be called with an empty string as the value of the Id parameter.

Because of the way that the MVC framework invokes controller actions, the URL /Home also matches the Index() method of the HomeController class in Listing 3.

Listing 3 - HomeController.cs (Index action with no parameter)

using System.Web.Mvc;namespace MvcApplication1.Controllers{ [HandleError] public class HomeController : Controller { public ActionResult Index() { return View(); } }}

The Index() method in Listing 3 does not accept any parameters. The URL /Home will cause this Index() method to be called. The URL /Home/Index/3 also invokes this method (the Id is ignored).

The URL /Home also matches the Index() method of the HomeController class in Listing 4.

Listing 4 - HomeController.cs (Index action with nullable parameter)

using System.Web.Mvc;namespace MvcApplication1.Controllers{ [HandleError] public class HomeController : Controller { public ActionResult Index(int? id) { return View(); } }}

In Listing 4, the Index() method has one Integer parameter. Because the parameter is a nullable parameter (can have the value Null), the Index() can be called without raising an error.

Finally, invoking the Index() method in Listing 5 with the URL /Home causes an exception since the Id parameter is not a nullable parameter. If you attempt to invoke the Index() method then you get the error displayed in Figure 1.

Listing 5 - HomeController.cs (Index action with Id parameter)

using System.Web.Mvc;namespace MvcApplication1.Controllers{ [HandleError] public class HomeController : Controller { public ActionResult Index(int id) { return View(); } }}

Figure 01: Invoking a controller action that expects a parameter value (Click to view full-size image)

The URL /Home/Index/3, on the other hand, works just fine with the Index controller action in Listing 5. The request /Home/Index/3 causes the Index() method to be called with an Id parameter that has the value 3.

Summary

The goal of this tutorial was to provide you with a brief introduction to ASP.NET Routing. We examined the default route table that you get with a new ASP.NET MVC application. You learned how the default route maps URLs to controller actions.

Next

ASP.NET MVC Routing Overview (C#) (2024)

FAQs

How routing works in MVC C#? ›

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller. The RouteConfig.

What is routing in MVC interview questions? ›

Routing – Routing is the first step in ASP.NET MVC pipelin Typically, it is a pattern matching system that matches the incoming request to the registered URL patterns in the Route Table.

What is ASP.NET Core MVC overview? ›

The ASP.NET Core MVC framework is a lightweight, open source, highly testable presentation framework optimized for use with ASP.NET Core. ASP.NET Core MVC provides a patterns-based way to build dynamic websites that enables a clean separation of concerns.

What are the 3 segments of the default route that is present in an ASP.NET MVC application? ›

The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id.

How many types of routing are there in C#? ›

There are two types of routing for action methods: Conventional Routing. Attribute Routing.

How many ways we can do routing in MVC? ›

Amongst these, the two most common ways happen to be conventional routing and attribute-based routing.
  • Conventional routing. Once a fresh ASP.net Core MVC application is created by making use of the default template, the app configures a default routing. ...
  • Multiple routes. ...
  • Attribute routing. ...
  • Conclusion.
Nov 9, 2021

How to explain MVC project in interview? ›

MVC is short for Model-View-Controller. An MVC design pattern divides applications into 3 parts - model, view, and controller. In MVC, "model" refers to business logic and the form of data. The "model" stores and maintains application data in databases.

Why MVC is better than asp net? ›

In addition to managing complexity, the MVC pattern makes it easier to test applications than it is to test a Web Forms-based ASP.NET Web application. For example, in a Web Forms-based ASP.NET Web application, a single class is used both to display output and to respond to user input.

Is ASP.NET Core MVC dead? ›

It is no longer in active development.

What is difference between MVC and .NET Core MVC? ›

Less code: ASP.NET Core MVC requires less code than ASP.NET MVC. Easy maintenance: . NET Core follows a modular approach due to Dependency Injection (DI). This makes it easier to manage and test individual services.

What is the overview of MVC? ›

MVC (Model-View-Controller) is a pattern in software design commonly used to implement user interfaces, data, and controlling logic. It emphasizes a separation between the software's business logic and display. This "separation of concerns" provides for a better division of labor and improved maintenance.

What are the two types of routing in MVC? ›

What are the two types of Routing. Convention-Based Routing and Attribute Routing are the two types of Routing.

What is the life cycle of MVC? ›

MVC is actually divided into two life cycles: the application life cycle and the request life cycle. The period from when the application process starts the active server to when it ends. Your application's startup file contains tags for the start and end events of the application.

How many types of filters are in MVC? ›

The Different Types of Filters

The ASP.NET MVC framework supports four different types of filters: Authorization filters – Implements the IAuthorizationFilter attribute. Action filters – Implements the IActionFilter attribute. Result filters – Implements the IResultFilter attribute.

How does attribute routing work in MVC? ›

ASP.NET MVC5 and WEB API 2 support a new type of routing, attribute routing. In this routing, attributes are used to define routes. Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application and WEB API.

How does MVC flow work? ›

First, the browser sends a request to the Controller. Then, the Controller interacts with the Model to send and receive data. The Controller then interacts with the View to render the data. The View is only concerned about how to present the information and not the final presentation.

How does routing work in Web API C#? ›

Once a matching route is found, Web API selects the controller and the action:
  • To find the controller, Web API adds "Controller" to the value of the {controller} variable.
  • To find the action, Web API looks at the HTTP verb, and then looks for an action whose name begins with that HTTP verb name.
May 9, 2022

How do routing paths work? ›

Routing works by finding the fastest and most efficient routes across a network. It takes place within routers – the hardware that decides which path data packets should take. Routers make these decisions using routing tables – lists of IP prefixes.

Top Articles
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 5952

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.