ASP.NET MVC以编程方式获取控制器列表

Den*_*oli 31 asp.net-mvc controller

在ASP.NET MVC中有没有办法通过代码枚举控制器并得到他们的名字?

例:

AccountController
HomeController
PersonController
Run Code Online (Sandbox Code Playgroud)

会给我一个列表,如:

Account, Home, Person
Run Code Online (Sandbox Code Playgroud)

gre*_*ade 43

使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*way 12

您可以通过程序集进行反映,并查找从System.Web.MVC.Controller类型继承的所有类.这是一些示例代码,展示了如何做到这一点:

http://mvcsitemap.codeplex.com/WorkItem/View.aspx?WorkItemId=1567