Pages

Monday, September 29, 2014

Attribute Based Routing


Developers who are working on MVC applications are familiar with the word called “Route” or Route table.  A Route is the URL specifying any access or Resource and “Routing” is the way of matching any action to URL. Earlier the Route needs to be added on the Route table and inside the RouteConfig.cs we have to call it. A typical Route was written like this.

routes.MapRoute(
name: "ItemPage",
url: "{itemId}/{itemTitle}",
defaults: new { controller = "Items", action = "Show" },
constraints: new { itemId = "\\d+" }
);      

In MVC 5 there is a new way of defining Rote is added called “Attribute Based Routing”, as the name clearly suggest that the routes are added just like any other attribute in MVC. This does not mean that the conventional based routing the old style is not supported it’s still there.

Now the earlier way of defining rotes were involved in the external routes files with exact controller and action method name. In the attribute based routing the routes are defined directly inside the controls action methods name thus it becomes easier to identify the routes and to the no of lines required to create a route is become a single line only.  We can write the above Rote in the easier way as  

[Route("{itemId:int}/{itemTitle}")]
public ActionResult ShowItem(int itemId)
{
  // Ur code goes here
}

Isn’t it easy? Yes it is, to enable attribute based routing we need to do some change in the Route.config file as follows. Use MapMvcAttributeRoutes as below. 

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

routes.MapMvcAttributeRoutes();
}
} 

The same can also be called inside the RegisterRoute methods with the other conventional routes. So now every method present inside a controller can have its own routes in the form of attribute. Or else if we want that some prefix to be fixed for all the action method present inside a controller then we can define it at the controller level like below.

[RoutePrefix("Sample")]
public class SampleController : Controller
{
// eg.: /sample/Index
public ActionResult Index()
{
         return View();
}

// eg.: /sample/About
public ActionResult About ()
 {
    return View();
  

By this all the Rotes will have a default prefix as “ Sample”. Hope you all have got idea that how to Use Attribute based routing and how to use a default prefix.  Now I will show that if there are some default prefix is set at a controller level but still if I want to override any of the default route then how can we do it.  For doing this we have to again call a specified rote with the Route attribute above the action method where we want to use it with a tilde (~) symbol. For example please check the below sample.

[RoutePrefix("Sample")]
public class SampleController : Controller
{
// eg.: /sample/Index
public ActionResult Index()
{
    return View();
}

// eg.: /sample/About
[Route(“~/Newsample/About”)]
public ActionResult About ()
 {
return View();
 }


Hope you have got idea that how to override the prefix for any specific action method.  Any The Same way we can specify the “Optional Parameter” for any route. Marking a optional parameter is very simple in attribute based routing as we simply need to add one Question mark (?) in the route as below.

public class HomeController : Controller
{
      [Route("home/{id?}")]
      public ActionResult Employee(int id)
      {
           ViewBag.Message = "This is Home Index Page";
           return View();
      }
}

This was simple. Hope You all have liked this article. On the Next article I will discuss about how to use Constraints in the Attribute based Routing. Please feel free to provide your valueable comment on this so that  I can improve more on it.

Thanks & Regards
Anil Kumar Pandey
Microsoft MVP, Microsoft MCC, DNS MVM


 

No comments:

Post a Comment

Kontera