Understanding attribute routing in ASP.NET MVC

Datetime:2016-08-23 04:39:36          Topic: ASP.NET MVC           Share

ASP.NET MVCandASP.NET WEB APIsupports new type of routing called Attribute routing .Here, as the name implies, the routing uses attributes for routing.It gives you more control over the URIs in your web application.Attribute routing provides you more control over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application andWEB API.The earlier style of routing  is called as convention based routing.To know more about convention based routing refer(in WEB API).

Enabling Attribute Routing in ASP.NET MVC

1.Enabling attribute routing is very very simple in ASP.MVC application.Go to Route.config file.Make a call in RegisterRoute method with map.MapMvcAttributeRoutes() .

2.Check below code.

public class RouteConfig
{
 public static void RegisterRoutes(RouteCollection routes)
 {
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 //enabling attribute routing
 routes.MapMvcAttributeRoutes();
 }
}

3.We can also combine both convention based routing and attribute routing like below.

4.Convention based routing is main routing mechanism in old ASP.NET MVC versions.

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 });
 }
}

Defining Attribute Routing in ASP.NET MVC

1.Controller level attribute routing

1.ASP.NET MVC 5 allows us to define routes at controller level to apply to all actions in specific controller unless we add a specific route to action.

2.Lets see how we can implement Controller level attribute routing in ASP.NET MVC.

[RoutePrefix("Home")] //Home controller
[Route("{action=index}")] //this is default action 
public class HomeController : Controller
{
 //Route: /Home/Index 
 public ActionResult Index()
 {
 return View();
 }
 
 //Route: /Home/About 
 public ActionResult About()
 {
 return View();
 }

2.Action level attribute routing

1.You can define routes at action level which apply to a specific action with in the controller.

2.See Action routing based routing ..

public class HomeController : Controller
{
 [Route("users/{id:int:min(100)}")] //route: /users/100
 public ActionResult Index(int id)
 {
 return View();
 }
 [Route("users/about")] //route-- /users/about
  //will be redirected to users controller,about action
 public ActionResult About()
 {
 ViewBag.Message = "Your application description page.";
 return View();
 }
}

Note:

1.We must configure attribute routing before conventional routing.

2.If we do not specify any route attributes in action based routing .The routing will work based on conventional based routing.

3.When you have only attribute routing, actions which do not have Route attribute for defining attribute-based routing will not be the part of attribute routing. In this way they can’t be access from outside as a URI.

When Attribute routing is better than Conventional routing

1.The convention-based routing is complex to support certain URI patterns that are common in RESTful APIs. But by using attribute routing you can define these URI patterns very easily.

2.For example, resources often contain child resources like Clients have orders, movies have actors, books have authors and so on.

3.It’s natural to create URIs that reflects these relations like as: /clients/1/orders This type of URI is difficult to create using convention-based routing. Although it can be done, the results don’t scale well if you have many controllers or resource types.

4.Using atrribute routing it is much easier to implement this type of URI in Attribute routing.

[Route("clients/{clientId}/orders")] 
public IEnumerable GetOrdersByClient(int clientId) 
{ 

}

Conclusion:

I hope this tutorial may helpful for many readers.Please subscribe to this blog www.mitechdev.com to get posts to your mail inbox.And follow through social networks(F acebook , twitter , google plus ) for daily updates...





About List