ASP.NET MVC4 List of all areas

2019-02-02 08:01发布

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.

2条回答
The star\"
2楼-- · 2019-02-02 08:21

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.

查看更多
We Are One
3楼-- · 2019-02-02 08:33

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.

查看更多
登录 后发表回答