Routing define the execution flow of incoming request to a controller and the functionality. System.Web.Routing is the namespace use for routing.  It is use of the MVC framework. Routing is introduced for eliminating the needs of mapping each URL with a physical file. It enables us to define URL patterns that maps to the request handler. It can be file or class In web form pplication request handler is .aspx file and in MVC it is Controller class and action method.

It is in the App_Start foler route.config.cs

using System;          
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace DemoStoreproc
{
    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 }
            );
        }
    }
}

 

Default schema is Home controller and Index action and id is optional. 

URL pattern in Routing

In the URL bar after the domain name URL pattern is considered. Format for URL pattern

Domain/controller/action

Routing in Asp.net with example

Multiple routes-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace DemoStoreproc
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(name: "Employee",
                url: "Employee",
                defaults: new {Controller="Employee",action="Index" });
 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

 

In the above code I have added custom route. It specifies that url starting with domain/Employee must be catch by Employee controller. In the url I have passed only controller I have not pass action because url starting with Employee controller must start with index action.

You can also visit related helpful posts

Routing in ASP.NET MVC

URL Routing in ASP.Net 3.5(IIS7)

URL Routing in MVC 4

How to angular routing html5mode in ASP.NET?

How route table is created in ASP.NET MVC4?

  Modified On Mar-17-2018 04:46:07 AM

Leave Comment