How to Create and Register a Route in ASP.NET MVC ?

The routes for the ASP.NET MVC Web Application is defined in the RouteConfig.cs under the App_Start folder of the ASP.NET MVC 4 Project.

How to Create and Register a Route in ASP.NET MVC ?

The RouteConfig.CS contains the following code.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

namespace Abundantcode

{

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 }

);

}

}

The RouteConfig contains a static RegisterRoutes function which is called from the Global.asax file.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http;

using System.Web.Mvc;

using System.Web.Optimization;

using System.Web.Routing;

namespace Abundantcode

{

// Note: For instructions on enabling IIS6 or IIS7 classic mode,

// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication

{

protected void Application_Start()

{

AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

RouteConfig.RegisterRoutes(RouteTable.Routes);

BundleConfig.RegisterBundles(BundleTable.Bundles);

}

}

}

The above method in the Global.asax is triggered when the application is started for the first time.

How to Create and Register a Route in ASP.NET MVC ?

To create and register a route in ASP.NET MVC , following steps are necessary

1. Identify URL pattern which will be used.

2. Add the new URL pattern to the RegisterRoute method . Below is a sample code snippet of the RouteConfig file which uses the Route class to create the necessary URL pattern and then add them to the RouteCollection with the Add method.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

namespace MvcApplication1

{

public class RouteConfig

{

public static void RegisterRoutes(RouteCollection routes)

{

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

Route myRoute = new Route("Abundantcode/{controller}/{action}", new MvcRouteHandler());

routes.Add("NewRoute", myRoute);

}

}

}

The URL for the above code will be something like this.

http://localhost:52677/Abundantcode/Employee/Index