反射找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         }
相關文章
相關標籤/搜索