这将为您提供一个字典,其中控制器类型为键,其MethodInfos的IEnumerable为值.
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); // currently loaded assemblies
var controllerTypes = assemblies
.SelectMany(a => a.GetTypes())
.Where(t => t != null
&& t.IsPublic // public controllers only
&& t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase) // enfore naming convention
&& !t.IsAbstract // no abstract controllers
&& typeof(IController).IsAssignableFrom(t)); // should implement IController (happens automatically when you extend Controller)
var controllerMethods = controllerTypes.ToDictionary(
controllerType => controllerType,
controllerType => controllerType.GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType)));
Run Code Online (Sandbox Code Playgroud)
它不仅仅查看当前程序集,还会返回方法,例如返回JsonResult而不是ActionResult.(JsonResult实际上继承自ActionResult)
编辑:用于Web API支持
更改
&& typeof(IController).IsAssignableFrom(t)); // should implement IController (happens automatically when you extend Controller)
Run Code Online (Sandbox Code Playgroud)
至
&& typeof(IHttpController).IsAssignableFrom(t)); // should implement IHttpController (happens automatically when you extend ApiController)
Run Code Online (Sandbox Code Playgroud)
并删除此:
.Where(m => typeof(ActionResult).IsAssignableFrom(m.ReturnType))
Run Code Online (Sandbox Code Playgroud)
因为Web API方法几乎可以返回任何内容.(POCO,HttpResponseMessage,......)
您可以使用它在运行时反映程序集,以在控制器中生成返回ActionResult的方法列表:
public IEnumerable<MethodInfo> GetMvcActionMethods()
{
return
Directory.GetFiles(Assembly.GetExecutingAssembly().Location)
.Select(Assembly.LoadFile)
.SelectMany(
assembly =>
assembly.GetTypes()
.Where(t => typeof (Controller).IsAssignableFrom(t))
.SelectMany(type => (from action in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
where action.ReturnType == typeof(ActionResult)
select action)
)
);
}
Run Code Online (Sandbox Code Playgroud)
这将为您提供操作,但不提供视图列表(即,如果您可以在每个操作中使用不同的视图,它将无法工作)
| 归档时间: |
|
| 查看次数: |
5744 次 |
| 最近记录: |