string InvokeMethod(PostRequest pr) { var type = this.GetType(); var mi = type.GetMethod(pr.MethodName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public); if (mi == null || mi.GetCustomAttributes(typeof(AjaxMethodAttribute), true).Length == 0) return "{\"error\": \"Method not found.\"}"; try { var pis = mi.GetParameters(); var args = new List<object>(); if (pr.Arguments.Count != pis.Length) return "{\"error\": \"Parameter count mismatch.\"}"; for (int i = 0; i < pis.Length; i++) { var pi = pis[i]; var arg = pr.Arguments[i]; var converter = TypeDescriptor.GetConverter(pi.ParameterType); if (converter != null) args.Add(converter.ConvertFromString(arg)); else args.Add(arg); } object ret = mi.Invoke(this, args.ToArray()); return string.Format("{{ \"result\": {0} }}", Utils.ConvertToJson(ret)); } catch (Exception e) { var ret = new Dictionary<string, object>(); ret["error"] = e.Message; ret["stackTrace"] = e.StackTrace; return Utils.ConvertToJson(ret); } }
PostRequest ParsePostData(string postData) { int pos = 0; if (!ReadDelimiter(postData, '{', ref pos)) return null; PostRequest request = new PostRequest(); while (pos < postData.Length) { string key = ReadString(postData, ref pos); if (!ReadDelimiter(postData, ':', ref pos)) break; object value = ReadValue(postData, ref pos); if (key == "method") request.MethodName = value as string; else if (key == "arguments") request.Arguments.AddRange(value as List<string>); ReadDelimiter(postData, ',', ref pos); if (pos < postData.Length && postData[pos] == '}') break; } return request; }