在ASP.NET MVC中,是否有一种通过代码枚举控制器并获取其名称的方法?
例如:
例如:
AccountController
HomeController
PersonController
将为我提供这样的列表:
Account, Home, Person
AccountController
HomeController
PersonController
将为我提供这样的列表:
Account, Home, Person
使用Jon的建议,通过反射程序集,以下是一个可能有用的片段:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
public class MvcHelper
{
private static List<Type> GetSubClasses<T>()
{
return Assembly.GetCallingAssembly().GetTypes().Where(
type => type.IsSubclassOf(typeof(T))).ToList();
}
public List<string> GetControllerNames()
{
List<string> controllerNames = new List<string>();
GetSubClasses<Controller>().ForEach(
type => controllerNames.Add(type.Name));
return controllerNames;
}
}
http://mvcsitemap.codeplex.com/WorkItem/View.aspx?WorkItemId=1567