Attribute Routing in ASP.NET MVC5 & WEB API2

ASP.NET MVC5 & WEB API2 implementing Attribute Routing directly over actions and controller.

 

Posted: January 23, 2019. | By: mustafa

ASP.NET MVC5 and WEB API 2 supports Attribute Routing. Attribute Routing allows us to define routes over actions and controllers in ASP.NET MVC5 and WEB API 2.

Two levels of Attribute Routing are:

 

Controller level attribute routing

We can define routes directly on controller which apply to all actions i the controller.

[RoutePrefix("NewHome")]
[Route("{action=index}")] // adding default action for the controller
public class HomeController : Controller
{
 //route: /NewHome/Index 
 public ActionResult Index()
 {
 return View();
 }
 
 //route: /NewHome/About-Us 
 [Route("about-us")]
 public ActionResult About()
 {
 ViewBag.Message = "Your application description page.";
 return View();
 }
 
 } 

 

Action level attribute routing

Defining routes for specific action within the controller.

public class HomeController : Controller
{
 [Route("employee/{id:int:min(100)}")] //route: /employee/100
 public ActionResult Index(int id)
 {
 //TO DO:
 return View();
 }
 
 [Route("employee/about")] //route: /employee/about
 public ActionResult About()
 {
 ViewBag.Message = "Your application description page.";
 return View();
 }
 }

Attribute Routing makes easy to create seo-friendly url's in Asp.Net MVC5. With conventional based routing we need to add & define routes in RouteConfig class but it becomes hard to manage when we have many routes to be defined for example in large applications.
With Attribute Routing helps us to define routes directly on to controller and its actions, also we can combine attribute routing with convention-based routing.

How to enabling Attribute Routing in ASP.NET MVC

Enabling attribute routing in your ASP.NET MVC5 application is simple, just add a call to routes.MapMvcAttributeRoutes() method with in RegisterRoutes() method of RouteConfig.cs file.

public class RouteConfig
 {
 public static void RegisterRoutes(RouteCollection routes)
 {
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 //enabling attribute routing
 routes.MapMvcAttributeRoutes();
 }
 
 //convention-based routing
 routes.MapRoute(
 name: "Default",
 url: "{controller}/{action}/{id}",
 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
 }

 

Hope this article helps to make understand attribute routing easier. Also read about how to implement convention-based routing in Asp.Net MVC in this article.


related posts

Back to top