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

时间:2009-07-20 05:33:05

标签: asp.net-mvc controller

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

示例:

AccountController
HomeController
PersonController

会给我一个列表,例如:

Account, Home, Person

4 个答案:

答案 0 :(得分:42)

使用Jon's suggestion of reflecting through the assembly,以下是您可能会觉得有用的代码段:

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;
    }
}

答案 1 :(得分:12)

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

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

答案 2 :(得分:0)

所有使用此帖子的人最好先阅读此帖:using Assembly.GetCallingAssembly() not returns the calling assembly

问题是剃刀视图充当独立的动态程序集,而您无法获得所需的程序集。

亚伊尔

答案 3 :(得分:-1)

在每个控制器中创建属性,然后得到这样的名称。