How to enable attribute routing in ASP .NET MVC?

To enable attribute routing in asp.net mvc we must call a method named “MapMvcAttributeRoutes” in RouteConfig class. The method “MapMvcAttributeRoutes” will be present in the class “RouteCollection” So we can call the method like below ,

routes.MapMvcAttributeRoutes();

Attribute Routing MVC
Attribute Routing MVC

The method will be executed while initializing the routers.
Description of the method from the class is “ Maps the attribute-defined routes for the application.”
Below is the full code of RouteConfig class with attribute routing enabled

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

Leave a Reply