o
MVC5 support a
new type of routing it’s called an attribute routing.
o
As the Name
implies routing uses attribute to
define routes.
o
The earlier style
of routing its called Convention based routing.
o
Still implement
attribute routing fully supported routing.
o
You can combine
convention based routing and attribute routing in same project is possible.
Why we can use Attribute Routing?
The previous version of asp.net MVC
using RouteConfig.cs file point Actual
controller.
public
class RouteConfig
{
public static void
RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account",
action = "Login", id =
UrlParameter.Optional }
);
}
}
When the
route definitions are co-located with the action. Within the same source file
rather than begin declared on an external configuration class.
How to use Attribute Routing:
It can be used routing call MapMVCAttributeRoutes during configuration.
public
class RouteConfig
{
public static void
RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMVCAttributeRoutes();
}
}
Both using
convention based routing and Attribute routing.
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 = "Account",
action = "Login", id =
UrlParameter.Optional }
);
}
}
Sample Syntax Attribute Routing:
public class TestController
: Controller
{
[Route("Test/(TitleID?)")]
public
ActionResult View(long TitleID)
{
return
View();
}
}