C# 通过反射获取MVC Controller里的类名,方法名,参数列表,返回值类型,Description描述,自定义Attribute
需要反射的DLL里的一个类:
namespace ElegantWM.WebUI.Areas.Admin.Controllers { [Description("功能模块管理")] public class ModuleController : BaseController { [Action] [Description("根据系统编号,获取系统的功能模块")] [HttpGet] public string Get(Guid sysId) { ... return json; } [Action] [Description("新建功能模块")] [HttpPost] public JsonResult Create(WMS_Module module) { ... } [Action] [Description("修改功能模块")] [HttpPut] public JsonResult Update(WMS_Module module) { ... } [Action] [Description("删除功能模块")] [HttpDelete] public JsonResult Delete(WMS_Module module) { ... } } }
反射代码:
Assembly assembly = Assembly.LoadFrom(@"ElegantWM.WebUI.dll"); var types = assembly.GetTypes(); foreach (var type in types) { if (type.BaseType.Name == "BaseController")//如果是Controller { var members = type.GetMethods(); foreach (var member in members) { //获取HTTPAttribute IEnumerable<Attribute> atts = member.GetCustomAttributes(); bool isAction = false; foreach (Attribute a in atts) { if (a.GetType().Name == "Action" || a.GetType().Name == "Page") { richTextBox1.AppendText(a.GetType().Name + "\r\n"); isAction = true; } else if (a.ToString().Contains("System.Web.Mvc.Http")) { richTextBox1.AppendText(a.GetType().Name.Replace("Http", "").Replace("Attribute", "") + "\r\n"); } } if (!isAction) continue; //获取返回值
richTextBox1.AppendText(member.ReturnType.Name + "\r\n"); //获取方法说明 object[] attrs = member.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true); if (attrs.Length > 0) richTextBox1.AppendText((attrs[0] as System.ComponentModel.DescriptionAttribute).Description + "\r\n"); //获取参数 ParameterInfo[] param = member.GetParameters(); StringBuilder sb = new StringBuilder(); foreach (ParameterInfo pm in param) { sb.Append(pm.ParameterType.Name + " " + pm.Name + ","); } richTextBox1.AppendText("(" + sb.ToString().Trim(',') + ")" + "\r\n"); //获取方法名称 richTextBox1.AppendText(member.Name + "\r\n"); //获取类名 richTextBox1.AppendText(member.DeclaringType.Name + "\r\n"); richTextBox1.AppendText("--------------------------\r\n"); } } }