Introduction


Routing is how ASP.NET MVC matches a URI to an Action.

"ASP.NET MVC 5 has a new feature called 'Attribute Routing' that allows a developer to specify the route of controller actions by adding Route Attributes to them. Developers can also add a RoutePrefix Attribute on the controller if each of the controller actions within that controller share a particular route prefix. I'll show a very basic example of this using a" SampleController "that will specify both a RoutePrefix on the controller as well as Route Attributes on each controller action" [David Hayden].

What is Attribute Routing?

ASP.NET "MVC 5 supports a new type of Routing, called Attribute Routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web application" [Ken Egozi].

Enable Routing Attributes

Turn on attribute based routing on RouteConfig file. You only need to add one new line of code to RegisterRoutes method.

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


Controller Routing

There are two "routing attributes [RoutePrefix] and [Route] that can be added at the controller level which apply to all actions within the controller unless a specific route is added to an action. For example, if every action in a controller should be under the path /sample/ and the default route should be to the Index action you could define your controller as"  [Matthew Mombrea] below.

"That will saves you from having to define a route prefix for every action in the controller. "  [Matthew Mombrea]

[RoutePrefix("sample")]
[Route("{action=index}")]
public class  SampleController : Controller
{
  public ActionResult Index()
  {
      return View();
  }
}
 

Routing Constraints

On this version, "you also gain the ability to apply routing constraints to your actions.

Similar to function overrides, a route will only be matched if the data type matches, otherwise the request will fall through to the next route matching the pattern, looking for a supported data type."
[Matthew Mombrea]

constraints list
Table by [Matthew Mombrea]

How to Set Route Constraints?

It allows you to restrict the parameters in the route. The syntax is {parameter:constraint}

   public class SampleController : Controller
{
        // eg: /Sample/20
        [Route("Sample/{sampleId:int}")]
        public ActionResult GetSpecificSampleById(int sampleId)
        {
            return View();
        }
 }

On this case, /Sample/20 will route to the action GetSpecificSampleById. This route only be selected if the sampleId is an integer.

MVC 5 Routing Resources

Some good online resources about ASP.NET MVC 5 Routing: