C#将dll中方法通过反射转换成Url以及反向解析
最近一个同事问我,他想实现在浏览器输入一个url,执行某个dll中的方法。
这个url的规则很简单:https://localhost:8080/命名空间/类名/方法名?param1=2¶m2=3.3
遇到这种问题,毫不犹豫,上反射。
/// <summary> /// 解析标准的url,通过反射调用对应的命名空间.类.方法 /// </summary> /// <param name="url"></param> /// <param name="dllPath"></param> public void ResolveUrlAndExcute(string url, string dllPath) { //https://localhost:8080/ClassLibrary1/MyClass/MyMethods?a=2&b=3.3 url = url.Replace("https://localhost:8080/", ""); string[] arr1 = url.Split("?"); string[] arr2 = arr1[0].Split("/"); string typeName = arr2[0] + "." + arr2[1]; string methodName = arr2[2]; List<object> listParameters = new List<object>(); string[] arr3 = arr1[1].Split("&"); foreach(string param in arr3) { listParameters.Add((object)param.Split("=")[1]); } var assembly = Assembly.LoadFile(dllPath); Type type = assembly.GetType(typeName);// namespace.class if(type != null) { MethodInfo methodInfo = type.GetMethod(methodName);// method name if(methodInfo != null) { object result = null; ParameterInfo[] parameters = methodInfo.GetParameters(); object classInstance = Activator.CreateInstance(type, null); if(parameters.Length == 0) { result = methodInfo.Invoke(classInstance, null); } else { result = methodInfo.Invoke(classInstance, listParameters.ToArray()); } } } }
如果想反向,把每一个方法转成标准的url,就更简单了。
/// <summary> /// 把dll中的方法通过反射转换成url /// </summary> /// <param name="dllPath"></param> /// <returns></returns> public static List<string> ComposeRequestUrl(string dllPath) { List<string> urls = new List<string>(); var assembly = Assembly.LoadFile(dllPath); foreach (var type in assembly.GetTypes()) { string baseUrl = "https://localhost:8080/" + type.Namespace + "/" + type.Name + "/"; MethodInfo[] myArrayMethodInfo = type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (var methodInfo in myArrayMethodInfo) { string url = baseUrl + methodInfo.Name + "?"; string retVal = string.Empty; if (methodInfo != null) { var parameters = methodInfo.GetParameters(); foreach (var param in parameters) { url += param.Name + "=&"; } } Debug.WriteLine(url.Substring(0, url.Length - 1)); urls.Add(url.Substring(0, url.Length - 1)); } } return urls; }