Overriding RouteArea and RoutePrefix Attributes (Useful for Legacy Routes)

mccalltd edited this page Sep 26, 2012 · 3 revisions

When supporting legacy URL’s, the automatic prefixing of routes with area names and route prefixes defined on an action’s controller can get in the way. Here’s a quick example of the problem and solution:

  [RoutePrefix("Current")]
  public class SomeController : ControllerBase    
  {
      [GET("Route", ActionPrecedence = 1)]
      [GET("Legacy-Route")] // This is a legacy url
      public ActionResult Index()
      {
          return View();
      }
  }

In this case, the Index action will match the following URL’s:

  • /Current/Route
  • /Current/Legacy-Route

What is intended, though, is that the following URL’s funnel into the Index action:

  • /Current/Route
  • /Legacy-Route (legacy)

In order to instruct the AttributeRouting library to support the second scenario, use the IsAbsoluteUrl property of the base RouteAttribute like so:

  [RoutePrefix("Current")]
  public class SomeController : ControllerBase    
  {
      [GET("Route", ActionPrecedence = 1)]
      [GET("Legacy-Route", IsAbsoluteUrl = true)] // This is a legacy url
      public ActionResult Index()
      {
          return View();
      }
  }

Also note that the ActionPrecedence property of the RouteAttribute is used to help determine which route is used for generating outbound URL’s.