在C#中,實現動態獲取類和方法主要經過反射來實現,要引用System.Reflection。json
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");