What Is Attribute based Routing?
MVC 5 supports a new type of routing that called
attribute routing. It used to define routes.
Enable Attribute Routing -
If you want to use Attribute Routing, you must enable it by calling
MapMvcAttributeRoutes on the RouteCollection.
public
class RouteConfig
{
public static
void RegisterRoutes(RouteCollection
routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enables Attribute Routing
routes.MapMvcAttributeRoutes();
}
}
Defining a Route -
A route attribute has to be defined on top of an action method or on the top of
a controller.
The Example looks like,
public
class HomeController:
BaseController
{
[Route("User/GetUsers")]
public ActionResult
GetUsers(int
Id)
{
return View();
}
}
Custom Routes -
public
class RouteConfig
{
public static
void RegisterRoutes(RouteCollection
routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name:
"User",
url:
"User/{id}",
defaults:
new { controller
= "User", action
= "Index"}
);
routes.MapRoute(
name:
"Default",
url:
"{controller}/{action}/{id}",
defaults:
new { controller
= "Home", action
= "Index",
id = UrlParameter.Optional
}
);
}
}