How to enable Attribute Routing in ASP.NET MVC?


Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file.

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

You can also combine attribute routing with convention-based routing.

public class RouteConfig 
{ 
    public static void RegisterRoutes(RouteCollection routes) 
    { 
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 
        //enabling attribute routing 
        routes.MapMvcAttributeRoutes(); 
        //convention-based routing 
        routes.MapRoute( 
            name: "Default", 
            url: "{controller}/{action}/{id}", 
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }); 
    } 
}