在C#中,实现动态获取类和方法主要通过反射来实现,要引用System.Reflection。
public ActionResult GetControllerAndAction() List<Type> controllerTypes = new List<Type>(); //创建控制器类型列表 var assembly = Assembly.Load("MySoft.UI"); //加载程序集 controllerTypes.AddRange(assembly.GetTypes().Where(type => typeof(IController).IsAssignableFrom(type) && type.Name!="ErrorController")); //获取程序集下所有的类,通过Linq筛选继承IController类的所有类型 StringBuilder jsonBuilder = new StringBuilder(); //创建动态字符串,拼接json数据 注:现在json类型传递数据比较流行,比xml简洁 jsonBuilder.Append("["); foreach (var controller in controllerTypes)//遍历控制器类 { jsonBuilder.Append("{"controllerName":""); jsonBuilder.Append(controller.Name); jsonBuilder.Append("","controllerDesc":""); jsonBuilder.Append((controller.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute)==null?"" : (controller.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute).Description); //获取对控制器的描述Description jsonBuilder.Append("","action":["); var actions = controller.GetMethods().Where(method => method.ReturnType.Name == "ActionResult"); //获取控制器下所有返回类型为ActionResult的方法,对MVC的权限控制只要限制所以的前后台交互请求就行,统一为ActionResult foreach (var action in actions) { jsonBuilder.Append("{"actionName":""); jsonBuilder.Append(action.Name); jsonBuilder.Append("","actionDesc":""); jsonBuilder.Append((action.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute) == null ? "" : (action.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute).Description); //获取对Action的描述 jsonBuilder.Append(""},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]},"); } jsonBuilder.Remove(jsonBuilder.Length - 1, 1); jsonBuilder.Append("]"); return Content(jsonBuilder.ToString(),"json/text");t");