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.

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I should have replied back earlier, but that is the solution I went with even before seeing your answer. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.