How To Enable Attribute Routing in ASP.Net MVC | ASP.Net MVC Interview Question

,
  • First, select the RouteConfig.cs inside the App_Start Folder.
  • After that call MapMvcAttributeRoutes is as below.

RouteConfig.cs

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

            routes.MapMvcAttributeRoutes();//Attribute Routing

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


Key points of the above code

  • To enable Attribute Routing,You have to callMapMvcAttributeRoutes on RouteConfig File.
  • If you want, You can keep the Convention-based Routing also with the same file is as above.
  • But routes.MapMvcAttributeRoutes(); Should configurebefore the Convention-based Routing.