在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");