zoukankan      html  css  js  c++  java
  • 反射找Controller中的方法

     1        /// <summary>
     2         /// 根据接口编码APICode,调用相应的webapi方法,注意返回值是json字符串
     3         /// </summary>
     4         /// <param name="apiCode">接口编码</param>
     5         /// <param name="requestJson">请求的json字符串</param>
     6         /// <returns>返回的json字符串</returns>
     7         public string Send(string apiCode, string requestJson)
     8         {
     9 
    10             var isExsitMethod = false;
    11             var resultJson = string.Empty;
    12             Assembly assembly = Assembly.GetExecutingAssembly(); //加载当前应用程序集
    13             Type[] typearr = assembly.GetTypes().Where(x => x.BaseType != null && x.BaseType.Name == "Controller").ToArray();
    14             //获取类型过滤掉非Controller控制器
    15             MethodInfo methodinfo = null;
    16             Type curtype = null;
    17             foreach (Type type in typearr) //针对每个类型获取详细信息
    18             {
    19                 methodinfo = type.GetMethod(apiCode); //获取方法信息
    20                 if (methodinfo != null)
    21                 {
    22                     isExsitMethod = true;
    23                     curtype = type;
    24                     break;
    25                 }
    26             }
    27             if (isExsitMethod)
    28             {
    29                 ParameterInfo[] paramsInfo = methodinfo.GetParameters(); //得到指定方法的参数列表 
    30                 Type tType = paramsInfo[0].ParameterType;
    31                 var obj = new object[1];
    32                 if (tType.IsClass) //如果是类,将它的json字符串转换成对象   
    33                 {
    34                     obj[0] = Newtonsoft.Json.JsonConvert.DeserializeObject(requestJson, tType);
    35 
    36                 }
    37                 object objtype = Assembly.GetExecutingAssembly().CreateInstance(curtype.FullName.ToString(), true, BindingFlags.Default, null, new object[0], null, null);
    38                 var response = methodinfo.Invoke(objtype, obj);
    39                 resultJson = SerializeHelper.ToJson(response);
    40                 return resultJson;
    41             }
    42 
    43             return string.Format("未找到方法{0}", apiCode);
    44 
    45         }
  • 相关阅读:
    mxGraph
    DrawIO二次开发(一)
    关于使用Draw.io画数据库E-R图的说明
    流程图软件draw.io值得你拥有
    diagrams
    http://www.avaloniaui.net/
    Qt音视频开发1-vlc解码播放
    Codeforces Round #548 (Div. 2) D 期望dp + 莫比乌斯反演
    线程
    牛客练习赛89E-牛牛小数点【数论】
  • 原文地址:https://www.cnblogs.com/hwisecn/p/6684769.html
Copyright © 2011-2022 走看看