Attribute Based Routing:
Routing is a process of mapping a virtual or nonexistent URL to a physical resource on server. Url Routing is not a new feature and traces of routing were always available in asp.net web forms from version 2.0.
If you have worked on web forms in asp.net 2.0 than you must remember the attribute called UrlMapping in web.config. Just to recap how that worked
<system.web>
<urlMappings>
<add url="~/cricket" mappedUrl="~/Home/Cricket.aspx"/>
</urlMappings>
</system.web>
Here the URL attribute is a virtual URL which is mapped to a physical URL mapped using mappedUrl attribute.
UrlMapping element provides us with basic routing. In Later versions and even in 2.0 we also created our custom Routing module to implement routing.
Asp.net MVC from its inception came equipped with URL Routing support. It’s very easy to create custom routes in MVC. Here is how basic MVC routing works
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 }
);
}
As you can see from above we have created a default route which maps to
http://Domain /Home/Index
Routes are added to a static routes collection and this it was not possible to add route information dynamically or customize routes based on actions in MVC. Routes till MVC 4.0 were too generic.
Asp.Net MVC introduced attribute based routing which means you can customize URL’s for controller as well as for actions.
Attribute routing is not enabled by default. You need to enable it in Route.config by adding below code:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}