简体   繁体   中英

ASP.NET MVC4 List of all areas

我有一个ASP.NET MVC4应用程序,我在其中创建多个区域,有没有一种方法可以通过编程方式找出存在的区域数量及其名称。

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.

AreaRegistration.RegisterAllAreas() cannot be used pre-initialization of the web application. However, if you want to get the areas without calling RegisterAllAreas() , eg 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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM