In .NET technology, we have seen lot of different ways to hit some specific resource or URI. In ASP.NET, we use Url Rewriting where as in ASP.NET MVC, there are two more options, first one is Convention Based Routing and other one is Attribute Routing.
What is Convention Based Routing in ASP.NET MVC?
Routing is a mechanism which is used to handle the incoming requests coming from browsers and it represent the particular action rather than any static or physical files. In ASP.NET, the Url hits any resources or files which physically exists but ASP.NET MVC Routing represents action. It is an approach to perform some action based on their definition defined in RouteConfig.cs.
Convention Based Routing
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.IgnoreRoute("favicon.ico");
- routes.IgnoreRoute("Content/img/dotnet-tutorial.ico");
- routes.MapRoute("LogOff", "logOff", new
- {
- controller = "Account", action = "logoff"
- });
- routes.MapRoute("Register", "register", new
- {
- controller = "Account", action = "Register"
- });
- routes.MapRoute("AboutUs", "aboutus", new
- {
- controller = "Home", action = "AboutUs"
- });
- routes.MapRoute("IndividualArticlesPost", "articles/{categoryslug}/{url}", new
- {
- controller = "Articles", action = "View"
- }, new
- {
- categoryslug = @ "\S+", url = @ "\S+"
- });
- routes.MapRoute("Default",
- "{controller}/{action}/{id}",
- new
- {
- controller = "Home",
- action = "Index",
- id = UrlParameter.Optional
- });
- }
In the above code, you can see three things: “routes”, “
IgnoreRoute” and “
MapRoute”.
Routes: It is nothing but only a table which is a collection of routes defined in route table. When someone hits some url in the browser, application first check the existing routes table and match with routes.
IgnoreRoute: It is also a collection of url that should be ignored by application.
MapRoute: It is used to add new route into the route table.
Attribute Routing
ASP.NET MVC also supports new type of routing that is called Attribute Routing. In this, attribute participate to route url to particular action.
To enable attribute routing, we need to use MapMvcAttributeRoutes() in the RouteConfig - public class RouteConfig
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapMvcAttributeRoutes();
-
- routes.MapRoute("LogOff", "logOff", new
- {
- controller = "Account", action = "logoff"
- });
- routes.MapRoute("Register", "register", new
- {
- controller = "Account", action = "Register"
- });
- routes.MapRoute("AboutUs", "aboutus", new
- {
- controller = "Home", action = "AboutUs"
- });
- routes.MapRoute("IndividualArticlesPost", "articles/{categoryslug}/{url}", new
- {
- controller = "Articles", action = "View"
- }, new
- {
- categoryslug = @ "\S+", url = @ "\S+"
- });
- routes.MapRoute("Default",
- "{controller}/{action}/{id}",
- new
- {
- controller = "Home",
- action = "Index",
- id = UrlParameter.Optional
- });
- }
- }
Note: Attribute Routing is configuring before the Convention Routing or simple Routing.
We can use
Convention based Routing and
Attribute Routing in the same project. Be sure attribute routing should be defined first to convention based routing.
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapMvcAttributeRoutes();
- routes.MapRoute(name: "Articles", url: "{controller}/{action}/{id}", defaults: new
- {
- controller = "Article", action = "Index", id = UrlParameter.Optional
- });
- routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new
- {
- controller = "Home", action = "Index", id = UrlParameter.Optional
- });
- }
Sample Example The following is a sample example of attribute routing. Here you can see we have used [Route] attribute to route the action with “
Home/Index”. When we define the Route attribute, it added route to route table and mapped with specific action.
- public class ArticleController: Controller
- {
- [Route("Home/Index")]
- public ActionResult Index()
- {
- return View();
- }
- }
Note: If route URI is not defined in attribute routing then it will work as Convention Routing.
Comman Route Prefix with Attribute Routing
To make your url neat, clear and user friendly, we can define the prefix in URL after domain name. We can use RoutePrefix attribute to define the prefix.
- [RoutePrefix("Articles")]
- public class ArticleController: Controller
- {
- [Route("{id}")]
- public ActionResult Details(int id)
- {
-
- }
- [Route("{username}")]
- public ActionResult MyArticleDetails(string username)
- {
-
- }
- }
Override the common route prefix with Attribute Routing
Sometimes, it is required to show different prefix in url with particular action. If you have already defined the Prefix for the whole controller then you can override it. To override the RoutePrefix, use ~ sign with prefix name with particular action in the Route attribute.
- [RoutePrefix("Articles")]
- public class ArticleController: Controller
- {
- [Route("~/ArticleList/{id}")]
- public ActionResult Details(int id)
- {
-
- }
- }
Route Constraints with Attribute Routing
When we use Route Constraints with Route attribute, it basically restrict or force how parameters will match.
- public class ArticleController: Controller
- {
- [Route("Articles/{id:int}")]
- public ActionResult Details(int id)
- {
-
- }
- [Route("Articles/{username}")]
- public ActionResult GetUserDetails(string username)
- {
-
- }
- }
In the above code, if you pass integer value as parameter after “
Articles/” then it will hit to first route otherwise second.
Attribute Routing in Area of ASP.NET MVC
In we are using Area in ASP.NET MVC project and want to use attribute routing, we need to use RouteArea attribute to define the area name and all will be same.
- [RouteArea("Admin")]
- [RoutePrefix("Home")]
- [Route("{action}")]
- public class HomeController: Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
-
- [Route("employees")]
- public ActionResult GetEmployees()
- {
- return View();
- }
-
- [Route("~/Department")]
- public ActionResult Departments()
- {
- return View();
- }
- }
Name attribute
As we use Custom Routing in ASP.NET MVC. We can achieve Custom Routing to define the Name of Route and use this route on the basis of Route name.
- [Route("Articles", Name = "MyArticle")]
- public ActionResult GetAllArticle()
- {
- }
- <a href="@Url.RouteUrl("MyArticle ")">My Article</a>
Which One is the Best
As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.
This is only my opinion; you can try it and see which one is better.
Thanks for reading this article, hope you enjoyed it.