MVC 5 Attribute Routing
I’m studying the Microsoft MVC 5 Framework. As part of my study practice, I force myself to write an article on the subject of whatever module I happen to be on. This helps me cement the idea in my own head while sharing my perspective on the lesson.
Hope this helps someone…..anyone. 😉
In the Model View Controller (MVC) framework, Routes determine which controller and method to execute for a specific URL.
A slightly easier way to state this is… routes tie specific set of code to website URL.
New in MVC 5, Microsoft introduced a cleaner way to do custom routes
This is an example of the old way to do routes, you might see it somewhere on a project.
RouteConfig.cs
routes.MapRoute(
“MoviesByReleaseDate”,
“movies/released/{year}/{month}”,
new { controller = “Movies”, action=”ByReleaseDate”},
new { year = @”2017|2018″, month = @”\d{2}” });
Controller code is not connected to the RouteConfig so if action name change is made in either one but not both, we have a big problem.
Instead of creating a messy RouteConfig file with lots of custom routes in it, we can now add custom routes by adding an attribute to the corresponding action.
To enable attribute routing we have to add a line to the RouteConfig file.
// EnableAttribute Routing
routes.MapMvcAttributeRoutes();
The entire file with new and old code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace Vidly
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
// Enable Attribute Routing
routes.MapMvcAttributeRoutes();
routes.MapRoute(
“MoviesByReleaseDate”,
“movies/released/{year}/{month}”,
new { controller = “Movies”, action=”ByReleaseDate”},
new { year = @”2017|2018″, month = @”\d{2}” });
routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}
}
}
Attribute Routes are added to the controller. In this case the MoviesController.cs file.
Example Attribute Route:
//Attribute Routes
[Route(“moives/released/{year}/{month:regex(\\d{2}):range(1, 12)}”)]
public ActionResult ByReleaseYear(int year, int month)
{
return Content(year + “/” + month);
}
In the example above, the month has a regex applied to it to match a pattern.
Will accept 2 digits \\d{2} and between a range of 1 to 12
There are other constraints we can apply that are supported by the framework
- Min
- Max
- Minlength
- Maxlength
- Int
- Float
- Guid
Google the term, “ASP.NET MVC Attribute Route Constraints” and you’ll find lots of online resources to help you.