Sunday, May 11, 2014

How To Create Custom Routes for MVC 4 Application

When you request any page into MVC Application, it will go through the Routing Architecture. Your Routing system will decide your URL pattern. The default routing algorithm is like {controller}/ {action}/ {id} patterns. But it can be possible to change that pattern using Custom Routes.




Default Route

goto App_Start > RouteConfig.cs
You wiil see -
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 }
            );
        }
       
    }

Custom Route

goto App_Start > RouteConfig.cs
and modify  cs file as following

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
               name: "Custom",
               url: "testCustom",
               defaults: new { controller = "Login", action = "Index", id = UrlParameter.Optional }
           );
 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
       
    }
your custom route has been created . Now when you will type "http://DefultUrl/testCustom" in browser  ,
 then login > index page  will be open.

No comments :

Post a Comment