惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
爱范儿
爱范儿
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
IT之家
IT之家
WordPress大学
WordPress大学
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
The GitHub Blog
The GitHub Blog
C
Check Point Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
G
Google Developers Blog
V
V2EX
雷峰网
雷峰网
美团技术团队
博客园 - 【当耐特】
人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
V
Visual Studio Blog
J
Java Code Geeks

博客园 - 北极熊,我来了!

使用JavaScript判断用户是否为手机设备 手机端页面自适应解决方案 Asp 邮件发送代码 js 日期字符串转换成日期类型,判断星期几 浅析a标签的4个伪类 C#读取Rss功能函数 《中文防止乱码的万能解决方案》 《小偷程序:自动获取百度天气预报》 Asp.NET使用HTML控件上传文件 《JS两级联动菜单学习全接触》 活动目录ADSI实现添加系统帐号问题!!! ADSI管理Windows2003系统帐号 中国频道空间使用Jmail发送邮件 《IP地址和数字之间转化的算法》 《单域名下整合动网、动易、OBlog程序》 JS读取XML数据 Asp.NET读取Excel数据 [XML系列]Flash读取XML数据 《省市联动功能菜单的实现》
C#获取类以及类下的方法(用于Asp.Net MVC)
北极熊,我来了! · 2016-05-30 · via 博客园 - 北极熊,我来了!

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