Now let’s discuss how to define the custom route in a cleaner way.
Look at this code. We currently have only one custom route, and if we’re working with larger applications this file will grow with lots of custom routes and over a period of time it will become a huge problem for us to handle all the routes. As we can see, each route consists of 3-4 lines of code, it is so time consuming and hard to keep in mind for logic building.
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- "StudentsByNamesAndDOB",
- "students/search/{name}/{year}",
- new { controller = "Students", action = "Index" });
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
Another issue with this approach is you need to move back and forth in the files like controller and RouteConfig to verify that the pattern you’re writing in your custom route will really works. You need to make sure the action name of the action.
And the third issue is if you go back to the studentscontroller and rename the action Index to Welcome then you need to keep in your mind that you’ll also update its relevant route.
- new { controller = "Students", action = "Welcome" }
So this code is fragile because of the magic strings.
In ASP.Net MVC 5, Microsoft has introduced a cleaner and better way to create the custom route. Instead of creating the route here, we can apply it using the attribute to the corresponding action. You might be thinking, then why learn an old and poor way of custom route? It's because you may be working with the existing code base with convention based custom routes so you need to understand how they work. But if you’re building a new application or improving an existing one, I would recommend you to use attribute routing.
Now let me show you how to define the custom route using an attribute.
First of all in order to use the attribute routing, you need to enable it here,
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapMvcAttributeRoutes(); // enabling
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
Now back to the controller.
- [Route("students/search/{name}/{year}")]
- public ActionResult Index(string name, int year)
- {
- var student = new Student
- {
- Name = "Usama",
- DOB = new DateTime(1900, 10, 25)
- };
- return View(student);
- }
Now if we want to apply the constraints here by month:
- [Route("students/search/{name}/{year:regex(\\d{2})}")]
- public ActionResult Index(string name, int year)
- {
- var student = new Student
- {
- Name = "Usama",
- DOB = new DateTime(1900, 10, 25)
- };
- return View(student);
- }
We can also apply more than one constraint on one item.
- [Route("students/search/{name}/{year:regex(\\d{2}):range(1, 20)}")]
- public ActionResult Index(string name, int year)
- {
- var student = new Student
- {
- Name = "Usama",
- DOB = new DateTime(1900, 10, 25)
- };
- return View(student);
- }
So you see attribute routes are more powerful and we also have a bunch of other constraints as well like min, max, minlength, maxlength, int, range, float, guid etc.
You don’t have to memorize any of these constraints just be aware that they are supported by the framework and whenever you need to know about their usage, just Google the things and you’ll find the result.
We can define the attribute routes at controller level as well. Actually we define the RoutePrefix which comes before the action route in the url.
- [RoutePrefix("candidate")]
- public class StudentsController : Controller
- {
- // GET: Students
- [Route("search/{name}/{year:regex(\\d{2}):range(1, 20)}")]
- public ActionResult Index(string name, int year)
- {
- var student = new Student
- {
- Name = "Usama",
- DOB = new DateTime(1900, 10, 25)
- };
- return View(student);
- }
- }
And now this ‘Index’ action will be accessible by this kind of route
http://localhost:64341/candidate/search/usama/15
Anyhow you can explore attribute routing in detail here.
Conclusion
As we can see attribute routing is so easy to implement and learn. We don't face any kind of difficulty to move back and forth in different files for the pattern. We don’t need to take care of the rules like we do in RouteConfig.cs. That route should be defined from the most specific to more generic. Here we need to just use the attributes on the top of the action and controller. Attribute routing provides us flexibility. And it is my kind suggestion that you must read out this article.
So if you’re working on a new project then it would be a better approach to define the attribute routes because conventional routing needs more effort and code.

Usama ShahidPosted May 10, 2018, 5:08 AM
Huy Dear, Nice To See you Here. First of all I would like to remind you everything which we can do with attribute routing, we can also doing that with conventional routing approach as well. Attribute Routing Technique is quite simple and flexible, it is easy to write. You're talking about the people who said that if the route are more complex then we should go with the attribute routing, actually these people have less knowledge of routing. I've seen some experienced developers as well who don't know the actual arrangement in which they should write the conventional route, the answer to this question always write the conventional route from more specific to more generic in RouteConfig, simple is that. Attribute routing are also helpful because when we see the action we also know that how to request this action, instead of opening the RouteConfig file and match the pattern and see the constraints which is really very time consuming. If you're starting a project then don't worry it is upto the your choice wheather you wanna go with conventional route or attribute route. I hope this detailed discussion answer your question. In additional see the question https://forums.asp.net/t/2139781.aspx?why+should+someone+go+for+attribute+routing+instead+of+conventional+routing
Tridip BhattacharjeePosted May 10, 2018, 4:40 AM
I heard but not sure. one people told me that few complex route can be compose using attribute routing instead of conventional routing. sir can you please show some routes which only can be compose by attribute routing and not possible by conventional routing. thanks
Tridip BhattacharjeePosted May 10, 2018, 4:37 AM
Sir very nice article. if am interested to know the advantage of attribute routing for which people follow it instead of conventional routing. please mention all points you consider as advantage of attribute routing. thanks