Routing

Last modified on April 14th, 2020 by DigitalIndiaInfo Team.


Routing in MVC

In the ASP.NET Web Forms application, every URL must match with a specific .aspx file. For example, a URL http://domain/ must match with the file employeesinfo.aspx that contains code and markup for rendering a response to the browser.

URL Controller Action Id
http://localhost/employee/123 employeeController Index 123
http://localhost/employee/index/123 employeeController Index 123
http://localhost/employee?Id=123 employeeController Index 123

Route Constraints

You can also apply restrictions on the value of parameter by configuring route constraints. For example, the following route applies a restriction on id parameter that the value of an id must be numeric.

So if you give non-numeric value for id parameter then that request will be handled by another route or, if there are no matching routes then "The resource could not be found" error will be thrown.

Register Routes

Now, after configuring all the routes in RouteConfig class, you need to register it in the Application_Start() event in the Global.asax. So that it includes all your routes into RouteTable.

Example: Route Registration
public class MvcApplication : System.Web.HttpApplication
                        {
                        protected void Application_Start()
                            {
                        RouteConfig.RegisterRoutes(RouteTable.Routes);
                        }
                            }
                        

The following figure illustrate Route registration process.

Register Route
Register Route

Thus, routing plays important role in MVC framework.

Points to Remember :
  1. Routing plays important role in MVC framework. Routing maps URL to physical file or class (controller class in MVC).
  2. Route contains URL pattern and handler information. URL pattern starts after domain name.
  3. Routes can be configured in RouteConfig class. Multiple custom routes can also be configured.
  4. Route constraints applies restrictions on the value of parameters.
  5. Route must be registered in Application_Start event in Global.ascx.cs file.


References :

  • www.tutorial.digitalindiainfo.com