ASP.NET MVC Programmatically Get a List of Controllers

Denny Ferrassoli picture Denny Ferrassoli · Jul 20, 2009 · Viewed 18.5k times · Source

In ASP.NET MVC is there a way to enumerate the controllers through code and get their name?

example:

AccountController
HomeController
PersonController

would give me a list such as:

Account, Home, Person

Answer

grenade picture grenade · Jul 20, 2009

Using Jon's suggestion of reflecting through the assembly, here is a snippet you may find useful:

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