C# 反射获取所有视图
原地址:忘了
controller 的 action 加上属性 [System.ComponentModel.Description("菜单列表")] 且 返回值为 System.Web.Mvc.ActionResult 类型,就可以获取到了
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
[System.ComponentModel.Description("菜单")] public ActionResult Index() { return View(DbContext.Menu.Where(c=>!c.IsDelete).OrderBy(c => c.Sort).ToList()); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 反射 获取方法 /// </summary> /// <returns></returns> public string GetMethodByReflect() { string strHtml = ""; var asm = System.Reflection.Assembly.GetExecutingAssembly(); System.Collections.Generic.List<Type> typeList = new List<Type>(); var types = asm.GetTypes(); foreach (Type type in types) { if (type.FullName.StartsWith("MyMVC.Controllers.") && type.FullName.EndsWith("Controller")) { typeList.Add(type); } } typeList.Sort(delegate (Type type1, Type type2) { return type1.FullName.CompareTo(type2.FullName); }); foreach (Type type in typeList) { System.Reflection.MemberInfo[] members = type.FindMembers(System.Reflection.MemberTypes.Method, System.Reflection.BindingFlags.Public | (System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly), Type.FilterName, "*"); //遍历成员 foreach (var m in members) { if (m.DeclaringType.Attributes.HasFlag(System.Reflection.TypeAttributes.Public) != true) { continue; } string controller = type.Name.Replace("Controller", ""); string action = m.Name; //str += $"{m.Name} - {type.FullName} - {m.DeclaringType.Attributes.ToString()}<br>"; MethodInfo method = type.GetMethod(m.Name); if ((method != null) && (method.ReturnType.ToString() == "System.Web.Mvc.ActionResult")) { var DescAttr = (System.ComponentModel.DescriptionAttribute)Attribute.GetCustomAttribute(m, typeof(System.ComponentModel.DescriptionAttribute)); if (DescAttr != null) { strHtml += $"{m.Name} - {DescAttr.Description} - {method.ReturnType.ToString()} - <br>"; } } } } return strHtml; }