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
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", // Route name
- "{controller}/{action}/{id}", // URL with parameters
- new
- {
- controller = "Home",
- action = "Index",
- id = UrlParameter.Optional
- });
- }
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.
![routing](/UploadFile/8a67c0/choose-attribute-routing-instead-of-convention-based-routing/Images/routing.png)
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}");
- // Attribute Routing
- routes.MapMvcAttributeRoutes();
- // Convention Based Routing
- 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", // Route name
- "{controller}/{action}/{id}", // URL with parameters
- new
- {
- controller = "Home",
- action = "Index",
- id = UrlParameter.Optional
- });
- }
- }
![Attribute routing](/UploadFile/8a67c0/choose-attribute-routing-instead-of-convention-based-routing/Images/Attribute routing.png)
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
- });
- }
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")] //Route: /Home/Index
- public ActionResult Index()
- {
- return View();
- }
- }
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}")] //Route: /Articles/13
- public ActionResult Details(int id)
- {
- //other code goes here
- }
- [Route("{username}")] //Route: /Articles/mukeshkumar
- public ActionResult MyArticleDetails(string username)
- {
- //other code goes here
- }
- }
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}")] //Route: /ArticleList/13
- public ActionResult Details(int id)
- {
- //other code goes here
- }
- }
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}")] //Route: /Articles/13
- public ActionResult Details(int id)
- {
- //other code goes here
- }
- [Route("Articles/{username}")] //Route: /Articles/mukeshkumar
- public ActionResult GetUserDetails(string username)
- {
- //other code goes here
- }
- }
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
- {
- // route: /Admin/Home/Index
- public ActionResult Index()
- {
- return View();
- }
- // route: /Admin/Home/Employees
- [Route("employees")]
- public ActionResult GetEmployees()
- {
- return View();
- }
- // route: /department
- [Route("~/Department")]
- public ActionResult Departments()
- {
- return View();
- }
- }
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>
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.
No comments:
Post a Comment