Today we are going to discuss a very important concept of MVC 5 and Web API 2 that is attribute routing. Attribute routing is used to define various attributes routing URL over controller and actions level. Up to mvc4 we learned about convention based routing. To implement attribute routing we have to enable it in routeconfig.cs class. After enabling attribute routing we can define multiple custom routes on controller and actions very easily so guys let’s start and see.
Convention based routing and attribute routing can be used together
How to enable attribute routing
<pre class="lang:c# decode:true"> public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapMvcAttributeRoutes(); }</pre>
routes.MapMvcAttributeRoutes() method is used to enable attribute routing.
now create a student controller and define following actions into it
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace RoutingInHindi.Controllers { [RoutePrefix("StudentData")] public class StudentController : Controller { // GET: Student [Route("AllStudents")] public ActionResult AllStudents() { return Content("All Students Return"); } [Route("Customer/{id?}")] public ActionResult CustomerbyId(int? id) { if(id>0) { return Content("Your ID is "+id.ToString()); } else { return Content("Please specify Id greator then 0"); } } } }
Now run program by and write following url in see result
http://localhost:52831/StudentData/AllStudents
http://localhost:52831/StudentData/Customer/2
Note : Please specify port number after localhost as per your system