Introduction

Routing is a pattern matching mechanism that accepts the incoming request and decides what to do with that request. At runtime, Routing engine makes use the Route table for matching the incoming request’s URL pattern with the URL patterns defined in the Global.asax.
As per your needs, you can register one or more URL patterns to the Route table at Application_Start event.

MVC-Routing

MVC-Routing

Below you can find simple routing rule that you can write inside RouteConfig.cs file.

  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 }
            );
        }
    }

In above example I have defined the Route Pattern for Routing purpose as {controller}/{action}/{id} and also provide the default values for a controller, action and id parameters. Default value mean if you do not provide the values for controller or action or id defined in the pattern(URL) then these values will be served by the routing system.

Let us elaborate above explanation with an example so you get the better idea about how it works. Let say your website is running on www.test.com then the URL pattern for your application will be www.test.com/{controller}/{action}/{id}. as a result, you have to provide the controller name followed by action name and id if it is required. If you do not provide any of the value then default values of these parameters will be provided by the routing engine.

Below I have provided some possiblelist of URLs that match and don’t match this route pattern.
(1) Request URL : http://test.com/
Matching Parameter : controller=Home, action=Index, id=none, Since default value of controller and action are Home and Index respectively.

(2) http://test.com/Admin
Matching Parameter : controller=Admin, action=Index, id=none, Since default value of action is Index.

(3) http://example.com/Admin/Product
Matching Parameter : controller=Admin, action=Product, id=none

(4) http://example.com/Admin/Product/1
Matching Parameter : controller=Admin, action=Product, id=1

(5) http://example.com/Admin/Product/SubAdmin/1
Matching Parameter :No Match Found (404)

(6) http://example.com/Admin/Product/SubAdmin/Save/1
Matching Parameter : No Match Found (404)

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website