ASP.NET MVC4 List of all areas

人盡茶涼 提交于 2019-11-29 00:23:41

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/15690834/asp-net-mvc4-list-of-all-areas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!