ResponseJsonMessage SendRequest(ParameterInfo[] argsName, RequestJsonMessage msg) { var hostAddress = HostAddress; string url; if (!string.IsNullOrEmpty(hostAddress.serviceNamePrefix)) { url = hostAddress.GetHttpAddress() + $"/{msg.Service}/{msg.Method}"; } else { url = hostAddress.GetHttpAddress() + $"/DynamicApi/{msg.Service}/{msg.Method}"; } var request = new ImitateWebRequest(HostAddress.address, Encoding.UTF8); request.ContentType = "application/json"; //var token = clientConnect.Token; var token = CreateAccessToken(argsName, msg.Args, clientConnect.TokenInfo); request.SetHead("token", token); var json = msg.Args.ToJson(); var result = request.Post(url, json); return(result.ToObject <ResponseJsonMessage>()); }
object SendRequest(serviceInfo serviceInfo, methodInfo method, object[] args) { //var method = serviceInfo.GetMethod(methodName); var serviceAttribute = serviceInfo.GetAttribute <ServiceAttribute>(); var methodAttribute = method.GetAttribute <MethodAttribute>(); var argsName = method.MethodInfo.GetParameters(); var returnType = method.MethodInfo.ReturnType; var contentType = ContentType.JSON; var serviceName = serviceInfo.ServiceType.Name; var hostAddress = HostAddress; if (serviceAttribute != null && serviceAttribute.ContentType != ContentType.NONE) { contentType = serviceAttribute.ContentType; if (!string.IsNullOrEmpty(serviceAttribute.Name)) { serviceName = serviceAttribute.Name; } if (!string.IsNullOrEmpty(serviceAttribute.GatewayPrefix)) { hostAddress.serviceNamePrefix = serviceAttribute.GatewayPrefix; } } var apiClientConnect = clientConnect as ApiClientConnect; var httpMethod = HttpMethod.POST; var responseContentType = contentType; var requestPath = $"/{apiClientConnect.Apiprefix}/{serviceName}/{method.MethodInfo.Name}"; if (methodAttribute != null) { httpMethod = methodAttribute.Method; if (!string.IsNullOrEmpty(methodAttribute.Path)) { requestPath = methodAttribute.Path; if (!requestPath.StartsWith("/")) { requestPath = "/" + requestPath; } } if (methodAttribute.ContentType != ContentType.NONE) { contentType = methodAttribute.ContentType; responseContentType = contentType; } if (methodAttribute.ResponseContentType != ContentType.NONE) { responseContentType = methodAttribute.ResponseContentType; } } var url = hostAddress.GetHttpAddress() + requestPath; var request = new ImitateWebRequest(ServiceName, apiClientConnect.Encoding); request.ContentType = ContentTypeDic[contentType]; string result; var firstArgs = args.FirstOrDefault(); var members = new Dictionary <string, object>(); #region 提交前参数回调处理 if (httpMethod == HttpMethod.POST && args.Count() == 1)//只有一个参数的POST { var type = firstArgs.GetType(); var pro = type.GetProperties(); if (firstArgs is System.Collections.IDictionary) { var dic = firstArgs as System.Collections.IDictionary; foreach (string key in dic.Keys) { members.Add(key, dic[key]); } } else { foreach (var p in pro) { members.Add(p.Name, p.GetValue(firstArgs)); } } } else { for (int i = 0; i < argsName.Length; i++) { var p = argsName[i]; var value = args[i]; members.Add(p.Name, value); } } #endregion try { apiClientConnect.OnBeforRequest?.Invoke(request, members, url); } catch (Exception ero) { throw new Exception("设置请求头信息时发生错误:" + ero.Message); } if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) { string data = ""; if (firstArgs != null) { if (contentType == ContentType.JSON) { data = members.ToJson(); } else if (contentType == ContentType.XML) { data = Core.SerializeHelper.XmlSerialize(firstArgs, apiClientConnect.Encoding); } else if (contentType == ContentType.FORM) { data = GetFormData(members); } else { data = firstArgs.ToString(); } } result = request.SendData(url, httpMethod.ToString(), data, out string nowUrl); } else { var list = new List <string>(); foreach (var kv in members) { list.Add(string.Format("{0}={1}", kv.Key, kv.Value)); } var str = string.Join("&", list); result = request.Get($"{url}?{str}"); } var generType = returnType; bool isTask = false; if (returnType.Name.StartsWith("Task`1")) { generType = returnType.GenericTypeArguments[0]; isTask = true; } object returnObj; try { if (responseContentType == ContentType.JSON) { returnObj = SerializeHelper.DeserializeFromJson(result, generType); } else if (responseContentType == ContentType.XML) { returnObj = SerializeHelper.XmlDeserialize(generType, result, apiClientConnect.Encoding); } else { returnObj = result; } } catch (Exception ero) { var eroMsg = $"反序列化为{generType.Name}时出错:" + ero.Message; Core.EventLog.Error(eroMsg + " " + result); throw new Exception(eroMsg); } if (isTask) { //返回Task类型 var method2 = typeof(Task).GetMethod("FromResult", BindingFlags.Public | BindingFlags.Static); var result2 = method2.MakeGenericMethod(new Type[] { generType }).Invoke(null, new object[] { returnObj }); return(result2); } return(returnObj); }
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { var methodInfo = serviceInfo.GetMethod(binder.Name); var id = Guid.NewGuid().ToString(); var method = ServiceType.GetMethod(binder.Name); var methodParamters = method.GetParameters(); var returnType = method.ReturnType; var request = new RequestJsonMessage { Service = ServiceName, Method = binder.Name, }; var allArgs = method.GetParameters(); request.Args = args.ToList(); var pollyAttr = serviceInfo.GetAttribute <PollyAttribute>(); //ResponseJsonMessage response = null; #region send var hostAddress = HostAddress; string url; if (!string.IsNullOrEmpty(hostAddress.serviceNamePrefix)) { //使用网关 url = hostAddress.GetHttpAddress() + $"/{request.Service}/{request.Method}"; } else { url = hostAddress.GetHttpAddress() + $"/{serviceInfo.ServiceAttribute.ApiPrefix}/{request.Service}/{request.Method}"; } var httpRequest = new ImitateWebRequest(HostAddress.address, Encoding.UTF8); httpRequest.ContentType = "application/json"; var token = CreateAccessToken(methodParamters, request.Args, clientConnect.TokenInfo); httpRequest.SetHead("token", token); #endregion var json = request.Args.ToJson(); Func <string, object> dataCall = (msg) => { var resMsg = msg.ToObject <ResponseJsonMessage>(); if (!resMsg.Success) { ThrowError($"服务端处理错误:{resMsg.Msg}", resMsg.Data); } if (resMsg.Outs != null && resMsg.Outs.Count > 0) { foreach (var kv in resMsg.Outs) { var p = allArgs[kv.Key]; var value = kv.Value; if (p.Name.EndsWith("&")) { var name = p.Name.Replace("&", ""); var type2 = Type.GetType(name); value = value.ToString().ToObject(type2); } args[kv.Key] = value; } } if (!string.IsNullOrEmpty(resMsg.Token)) { clientConnect.TokenInfo.Token = resMsg.Token; } var generType = returnType; if (methodInfo.IsAsync) { generType = returnType.GenericTypeArguments[0]; } //转换为实际的数据类型 return(resMsg.GetData(generType)); }; if (returnType == typeof(void)) { result = null; return(true); } if (methodInfo.IsAsync) { var asynResult = SendRequestAsync(pollyAttr, httpRequest, url, "POST", json, $"{ServiceName}.{method.Name}", dataCall); var task = methodInfo.TaskCreater(); task.ResultCreater = async() => { return(await asynResult); }; result = task.InvokeAsync(); } else { result = SendRequest(pollyAttr, httpRequest, url, "POST", json, $"{ServiceName}.{method.Name}", dataCall); } return(true); }
object SendRequest(serviceInfo serviceInfo, methodInfo methodInfo, object[] args) { //var method = serviceInfo.GetMethod(methodName); var serviceAttribute = serviceInfo.GetAttribute <ServiceAttribute>(); var methodAttribute = methodInfo.GetAttribute <MethodAttribute>(); var argsName = methodInfo.MethodInfo.GetParameters(); var returnType = methodInfo.MethodInfo.ReturnType; var contentType = ContentType.JSON; var serviceName = serviceInfo.ServiceType.Name; var hostAddress = HostAddress; if (serviceAttribute != null && serviceAttribute.ContentType != ContentType.NONE) { contentType = serviceAttribute.ContentType; if (!string.IsNullOrEmpty(serviceAttribute.Name)) { serviceName = serviceAttribute.Name; } if (!string.IsNullOrEmpty(serviceAttribute.GatewayPrefix)) { hostAddress.serviceNamePrefix = serviceAttribute.GatewayPrefix; } } var apiClientConnect = clientConnect as ApiClientConnect; var httpMethod = HttpMethod.POST; var responseContentType = contentType; var requestPath = $"/{apiClientConnect.Apiprefix}/{serviceName}/{methodInfo.MethodInfo.Name}"; if (methodAttribute != null) { httpMethod = methodAttribute.Method; if (!string.IsNullOrEmpty(methodAttribute.Path)) { requestPath = methodAttribute.Path; if (!requestPath.StartsWith("/")) { requestPath = "/" + requestPath; } } if (methodAttribute.ContentType != ContentType.NONE) { contentType = methodAttribute.ContentType; responseContentType = contentType; } if (methodAttribute.ResponseContentType != ContentType.NONE) { responseContentType = methodAttribute.ResponseContentType; } } var url = hostAddress.GetHttpAddress() + requestPath; var request = new ImitateWebRequest(ServiceName, apiClientConnect.Encoding); request.ContentType = ContentTypeDic[contentType]; //string result; var firstArgs = args.FirstOrDefault(); var members = new Dictionary <string, object>(); #region 提交前参数回调处理 if (httpMethod == HttpMethod.POST && args.Count() == 1)//只有一个参数的POST { var type = firstArgs.GetType(); var pro = type.GetProperties(); if (firstArgs is System.Collections.IDictionary) { var dic = firstArgs as System.Collections.IDictionary; foreach (string key in dic.Keys) { members.Add(key, dic[key]); } } else { foreach (var p in pro) { members.Add(p.Name, p.GetValue(firstArgs)); } } } else { for (int i = 0; i < argsName.Length; i++) { var p = argsName[i]; var value = args[i]; members.Add(p.Name, value); } } #endregion //try //{ // apiClientConnect.OnBeforRequest?.Invoke(request, members, url); //} //catch (Exception ero) //{ // throw new Exception("设置请求头信息时发生错误:" + ero.Message); //} if (requestHeads != null) { foreach (var kv in requestHeads) { request.SetHead(kv.Key, kv.Value); } } string postArgs = ""; if (httpMethod != HttpMethod.GET) { if (firstArgs != null) { if (contentType == ContentType.JSON) { postArgs = members.ToJson(); } else if (contentType == ContentType.XML) { postArgs = Core.SerializeHelper.XmlSerialize(firstArgs, apiClientConnect.Encoding); } else if (contentType == ContentType.FORM) { postArgs = GetFormData(members); } else { postArgs = firstArgs.ToString(); } } } else { var list = new List <string>(); foreach (var kv in members) { list.Add(string.Format("{0}={1}", kv.Key, kv.Value)); } var str = string.Join("&", list); url = $"{url}?{str}"; //result = request.Get($"{url}?{str}"); } bool isTask = methodInfo.IsAsync; var generType = returnType; if (isTask) { generType = returnType.GenericTypeArguments[0]; } var pollyAttr = serviceInfo.GetAttribute <PollyAttribute>(); Func <string, object> dataCall = (msg) => { apiClientConnect.OnAfterRequest?.Invoke(url, msg); object returnObj = msg; try { if (generType != typeof(string)) { if (responseContentType == ContentType.JSON) { returnObj = SerializeHelper.DeserializeFromJson(msg, generType); } else if (responseContentType == ContentType.XML) { returnObj = SerializeHelper.XmlDeserialize(generType, msg, apiClientConnect.Encoding); } } } catch (Exception ero) { var eroMsg = $"反序列化为{generType.Name}时出错:" + ero.Message; Core.EventLog.Error(eroMsg + " " + msg); throw new Exception(eroMsg); } //转换为实际的数据类型 return(returnObj); }; if (methodInfo.IsAsync) { var asynResult = SendRequestAsync(pollyAttr, request, url, httpMethod.ToString(), postArgs, $"{ServiceName}.{methodInfo.MethodInfo.Name}", dataCall); var task = methodInfo.TaskCreater(); task.ResultCreater = async() => { return(await asynResult); }; return(task.InvokeAsync()); } return(SendRequest(pollyAttr, request, url, httpMethod.ToString(), postArgs, $"{ServiceName}.{methodInfo.MethodInfo.Name}", dataCall)); }