ASP.NET MVC Programmatically Get a List of Controllers

前端 未结 4 2039
轻奢々
轻奢々 2020-11-30 03:57

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

example:

AccountController
HomeController
PersonControlle         


        
相关标签:
4条回答
  • 2020-11-30 04:21

    You can reflect through your assembly and find all classes which inherit from type System.Web.MVC.Controller. Here's some sample code that shows how you could do that:

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

    0 讨论(0)
  • 2020-11-30 04:22

    Create the property in every controller and then you get the name like this.

    0 讨论(0)
  • 2020-11-30 04:31

    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;
        }
    }
    
    0 讨论(0)
  • 2020-11-30 04:31

    All who using this post better read this post before: using Assembly.GetCallingAssembly() not returns the calling assembly

    The issue is that razor views are acting as independent dynamic assemblies and you don't get the desired assembly.

    Yair

    0 讨论(0)
提交回复
热议问题