反射找Controller中的方法

Posted on 2017-04-09 14:59  hwisecn  阅读(456)  评论(0编辑  收藏  举报
 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         }

 

Copyright © 2024 hwisecn
Powered by .NET 9.0 on Kubernetes