简体   繁体   English

ASP.NET MVC4所有领域的列表

[英]ASP.NET MVC4 List of all areas

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

The AreaRegistration.RegisterAllAreas(); AreaRegistration.RegisterAllAreas(); registers each area route with the DataTokens["area"] where the value is the name of the area. 使用DataTokens["area"]注册每个区域路径,其中值是区域的名称。

So you can get the registered area names from the RouteTable 因此,您可以从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自己,你可以使用反射来获取从派生类型AreaRegistration在assambly。

AreaRegistration.RegisterAllAreas() cannot be used pre-initialization of the web application. AreaRegistration.RegisterAllAreas()不能用于Web应用程序的预初始化。 However, if you want to get the areas without calling RegisterAllAreas() , eg in an automated test, then the following code may be helpful: 但是,如果您想在不调用RegisterAllAreas()情况下获取区域,例如在自动化测试中,则以下代码可能会有所帮助:

     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 . 请注意, MvcApplication是从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 . 只要该类与程序集注册在同一程序AreaRegistration ,即从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. 如果您将应用程序与多个程序集中的区域分开,则需要相应地调整此代码,以便搜索所有这些程序集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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