0

I have an old MVC3 site where I was able to get the area of a route by using the following code:

object oArea;

RouteData.DataTokens.TryGetValue("area", out aArea);

I am creating a new MVC5 application and have started to use attribute based routing as follows:

[RouteArea("Area")]
[RoutePrefix("Test")]
public TestController
{
    public ActionResult Index()
    {
         return View("Index");
    }
}

Unfortunately, it appears that when you use attribute based routing then the RouteData.DataTokens collection is empty. The area information appears buried under the RouteData in "MS_DirectRouteMatches", so you could get the data as follows:

RouteData.Values["MS_DirectRouteMatches"])[0].DataTokens.TryGetValue("area", out oArea);

However, I was wondering if there is an easier, safer or better way to get the area data in MVC5. The area name is actually the sub-tool name within a larger application, which is used for some logic in the base controller initialization.

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
wigs
  • 239
  • 2
  • 11

1 Answers1

1

The only "safe" way is to first check for the existence of the MS_DirectRouteMatches and only probe for the area if it exists, falling back to the original RouteData object if it does not.

string area;
RouteData routeData = HttpContext.Request.RequestContext.RouteData;

if (routeData != null)
{
    if (routeData.Values.ContainsKey("MS_DirectRouteMatches"))
    {
        routeData = ((IEnumerable<RouteData>)routeData.Values["MS_DirectRouteMatches"]).First();
    }
    routeData.DataTokens.TryGetValue("area", out area);
}
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • I should have replied back earlier, but that is the solution I went with even before seeing your answer. Thanks. – wigs Apr 24 '15 at 15:32