Tuesday, January 9, 2018

Routing in ASP.Net MVC

ASP.Net MVC routing is a pattern matching system whihc is responsible for mapping incoming browser request to specific MVC controller actions.

When ASP .Net appliation launches then the application register one or more patterns with the framework route table to inform the routing engine what to do with the request that matches those patern. When the routing engine receives a request at runtime, it matches the request URL with the URL pattern registered with it and gives the response accordingly.

ASP .Net routing is setup in two places.

First in Web Config file : There are four section related to it (system.web.httpModules,system.web.httpHandlers,system.webserver.modules and system.webserver.handlers)

Second in Global.asax file : Here route table is created and RegisterRoutes method called

  protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }

When the request URL matches any registered route pattern in the route table then the routing engine forward the request to appropriate handler for the request, Thereafter the route is processed and gets a view on the UI. Otherwise 04 HTTP status code returned.

Properties of Route:

Route Name : A name unique give to that route.

Url :  Where Url pattern is define like {controller}/{action}/{id}

defaults: You can assign default value for paramtere controller,action and id

Constraints : A set of constraints to apply against the URL pattern.

When Launches the application first of all Application_Start event handler call the RegisterRoutes() method from RouteConfig class. It has a parameter called route which is a Collection of routes that contains all the registered routes in the application.

 public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

  routes.MapRoute(
            name: "Student",
            url: "students/{id}",
            defaults: new { controller = "Student", action = "Index"}
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        }

No comments:

Followers

Link