Question

I have an ASP.NET MVC4 application in which I am creating multiple areas, is there a way I can find out programmatically the number of areas that are present and their names.

Was it helpful?

Solution

The AreaRegistration.RegisterAllAreas(); registers each area route with the DataTokens["area"] where the value is the name of the area.

So you can get the registered area names from the RouteTable

var areaNames = RouteTable.Routes.OfType<Route>()
    .Where(d => d.DataTokens != null && d.DataTokens.ContainsKey("area"))
    .Select(r => r.DataTokens["area"]).ToArray();

If you are looking for the AreaRegistration themselves you can use reflection to get types which derives from AreaRegistration in your assambly.

OTHER TIPS

AreaRegistration.RegisterAllAreas() cannot be used pre-initialization of the web application. However, if you want to get the areas without calling RegisterAllAreas(), e.g. in an automated test, then the following code may be helpful:

     var areaNames = new List<string>();
     foreach (var type in typeof(MvcApplication).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(AreaRegistration)))) {
        var areaRegistration = Activator.CreateInstance(type) as AreaRegistration;
        areaNames.Add(areaRegistration.AreaName);
     }

Note that MvcApplication is the class derived from HttpApplication. You can use any class name as long as that class is in the same assembly as the assembly registrations, i.e. the classes derived from AreaRegistration. If you have split up your application with areas in more than one assembly, then you'd need to adapt this code accordingly so it searches all those assemblies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top