/// <summary> /// 从契约中反序列化取参数列表 /// </summary> /// <param name="theContract">方法数据契约</param> /// <returns>参数列表</returns> private List <object> GetParamList(MethodDC theContract) { List <object> relParamList = new List <object>(); foreach (ParameterDC aparamet in theContract.ParameterList) { Type relType = Type.GetType(aparamet.TypeQualifiedName); object value = Serializer.Deserialize(aparamet.JsonValue, relType); relParamList.Add(value); } return(relParamList); }
public ApiCore(MethodDC Contract) { Serializer = ServiceTaker.GetService <IJsonSerializer>(); theContract = Contract; }
public object RequseteWeb(string apiMapKey, string apiInterfaceName, string methodName, List <object> parameterList, string[] types, string apiUrl = "") { HttpWebResponse response = null; Stream streamResponse = null; try { MethodDC theContract = new MethodDC(); theContract.ApiConfigKey = apiMapKey; theContract.InterfaceName = apiInterfaceName; theContract.MethodName = methodName; theContract.TypeArguments = types; List <ParameterDC> webParamerList = new List <ParameterDC>(); foreach (object param in parameterList) { ParameterDC aWebParamer = new ParameterDC(); aWebParamer.TypeQualifiedName = param.GetType().AssemblyQualifiedName; aWebParamer.JsonValue = Serializer.Serialize(param); webParamerList.Add(aWebParamer); } theContract.ParameterList = webParamerList; string jsonContract = Serializer.Serialize(theContract); //TODO:加密或压缩对jsonContract,密文可根据日期变化。服务端验证密文 MethodDC vdf = Serializer.Deserialize <MethodDC>(jsonContract); byte[] PostData = Encoding.UTF8.GetBytes(jsonContract); var watch = new System.Diagnostics.Stopwatch(); watch.Start(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.GetRequestStream().Write(PostData, 0, PostData.Length); request.ContentType = "text/xml"; ServicePoint currentServicePoint = request.ServicePoint; currentServicePoint.ConnectionLimit = 1000; response = (HttpWebResponse)request.GetResponse(); streamResponse = response.GetResponseStream(); string strResponse = string.Empty; //如果服务端采用了GZIP压缩,则先解压缩。 if (response.ContentEncoding.ToLower().Contains("gzip")) { using (GZipStream gz = new GZipStream(streamResponse, CompressionMode.Decompress)) { using (StreamReader readerGzip = new StreamReader(gz, Encoding.UTF8)) { strResponse = readerGzip.ReadToEnd(); } } } else { using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8)) { strResponse = streamRead.ReadToEnd(); } } //TODO:解密或解压缩对strResponse MethodDC reObj = Serializer.Deserialize <MethodDC>(strResponse); watch.Stop(); //写请求日志,用于跟踪请求的时间和数据大小。 string writeWebRequestLog = System.Configuration.ConfigurationManager.AppSettings["WriteClientHttpWebRequestLog"]; if (writeWebRequestLog == null) { writeWebRequestLog = "false"; } if (bool.Parse(writeWebRequestLog) && !apiInterfaceName.Contains("DBClientBase")) { Task task = Task.Factory.StartNew(() => { byte[] responseData = Encoding.UTF8.GetBytes(strResponse); var counter = watch.ElapsedMilliseconds; string Parameters = ""; for (int i = 0; i < theContract.ParameterList.Count; i++) { Parameters += theContract.ParameterList[i].JsonValue + "@"; } CountUserData countUserData = new CountUserData { ApiInterfaceName = apiInterfaceName, ClientComputerIP = UserProfiles.ClientComputerGuid, UserName = UserProfiles.UserName, LocationName = UserProfiles.HospitalName, MethodName = methodName, CounterTime = counter, ResponseData = (responseData.Length / 1024.00).ToString("f0"), OperTime = DateTime.Now, ParameterContents = Parameters, }; Orm.Config.Service.DBClientService.Add <CountUserData>(countUserData); }); //string strRequestTimeLog = string.Format(" 诊所:{0} ip地址:{1} 操作人:{2} 操作时间:{3} 接口:{4}调用方法:{5} 请求响应时间:{6}(毫秒) 返回值大小:{7}Kb", // UserProfiles.LocationName, UserProfiles.ClientComputerGuid,UserProfiles.UserName,DateTime.Now, apiInterfaceName, methodName, counter.ToString(), (responseData.Length / 1024.00).ToString("f0")); //WriteLog(strRequestTimeLog, null); } if (reObj.Result.HasException) { if (reObj.Result.ExceptionState == 1) { System.Windows.Forms.MessageBox.Show(reObj.Result.ExceptionMessage, "消息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); return(null); } else if (reObj.Result.ExceptionState == 2) { System.Windows.Forms.MessageBox.Show(reObj.Result.ExceptionMessage, "警告", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return(null); } else if (reObj.Result.ExceptionState == 3) { System.Windows.Forms.MessageBox.Show(reObj.Result.ExceptionMessage, "错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return(null); } else { throw new Exception("Message: " + reObj.Result.ExceptionMessage + "\r\n" + "Stack: " + reObj.Result.ExceptionStack); } } else { Type relType = Type.GetType(reObj.Result.TypeQualifiedName); object relResult = null; if (relType.Name.ToLower() != "void") { relResult = Serializer.Deserialize(reObj.Result.JsonValue, relType); } return(relResult); } } finally { if (streamResponse != null) { streamResponse.Close(); } if (response != null) { response.Close(); } } }
/// <summary> /// http请求(行心云) /// </summary> /// <param name="apiMapKey"></param> /// <param name="apiInterfaceName"></param> /// <param name="methodName"></param> /// <param name="parameterList"></param> /// <param name="types"></param> /// <param name="apiUrl"></param> /// <returns></returns> public object HttpRequest(string apiInterfaceName, string methodName, List <object> parameterList, string[] types, string apiUrl = "") { HttpWebResponse response = null; Stream streamResponse = null; try { MethodDC transDataClass = new MethodDC(); transDataClass.ApiConfigKey = apiInterfaceName; transDataClass.InterfaceName = apiInterfaceName; transDataClass.MethodName = methodName; transDataClass.TypeArguments = types; List <ParameterDC> webParamerList = new List <ParameterDC>(); foreach (object param in parameterList) { ParameterDC aWebParamer = new ParameterDC(); aWebParamer.TypeQualifiedName = param.GetType().AssemblyQualifiedName; aWebParamer.JsonValue = JsonConvert.SerializeObject(param); webParamerList.Add(aWebParamer); } transDataClass.ParameterList = webParamerList; //将要传递的数据序列化成json格式 string jsonContract = JsonConvert.SerializeObject(transDataClass); //TODO:加密或压缩对jsonContract,密文可根据日期变化。服务端验证密文 MethodDC vdf = JsonConvert.DeserializeObject <MethodDC>(jsonContract); //将要传递的json转成byte[] byte[] PostData = Encoding.UTF8.GetBytes(jsonContract); var watch = new System.Diagnostics.Stopwatch(); watch.Start(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.GetRequestStream().Write(PostData, 0, PostData.Length); request.ContentType = "text/xml; charset=utf-8"; ServicePoint currentServicePoint = request.ServicePoint; currentServicePoint.ConnectionLimit = 1000; response = (HttpWebResponse)request.GetResponse(); streamResponse = response.GetResponseStream(); string strResponse = string.Empty; //如果服务端采用了GZIP压缩,则先解压缩。 if (response.ContentEncoding.ToLower().Contains("gzip")) { using (GZipStream gz = new GZipStream(streamResponse, CompressionMode.Decompress)) { using (StreamReader readerGzip = new StreamReader(gz, Encoding.UTF8)) { strResponse = readerGzip.ReadToEnd(); } } } else { using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8)) { strResponse = streamRead.ReadToEnd(); } } //TODO:解密或解压缩对strResponse MethodDC reObj = JsonConvert.DeserializeObject <MethodDC>(strResponse); watch.Stop(); //写请求日志,用于跟踪请求的时间和数据大小。 string writeWebRequestLog = System.Configuration.ConfigurationManager.AppSettings["WriteClientHttpWebRequestLog"]; if (writeWebRequestLog == null) { writeWebRequestLog = "false"; } if (bool.Parse(writeWebRequestLog) && watch.ElapsedMilliseconds > 1000) { byte[] responseData = Encoding.UTF8.GetBytes(strResponse); var counter = watch.ElapsedMilliseconds; string strRequestTimeLog = string.Format(" 接口:{0} 调用方法:{1} 请求响应时间:{2}(毫秒) 返回值大小:{3}Kb", apiInterfaceName, methodName, counter.ToString(), (responseData.Length / 1024.00).ToString("f0")); WriteLog(strRequestTimeLog, null); } if (reObj.Result.HasException) { if (reObj.Result.ExceptionState == 1) { System.Windows.Forms.MessageBox.Show(reObj.Result.ExceptionMessage, "消息", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); return(null); } else if (reObj.Result.ExceptionState == 2) { System.Windows.Forms.MessageBox.Show(reObj.Result.ExceptionMessage, "警告", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); return(null); } else if (reObj.Result.ExceptionState == 3) { System.Windows.Forms.MessageBox.Show(reObj.Result.ExceptionMessage, "错误", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error); return(null); } else { throw new Exception("Message: " + reObj.Result.ExceptionMessage + "\r\n" + "Stack: " + reObj.Result.ExceptionStack); } } else { Type relType = Type.GetType(reObj.Result.TypeQualifiedName); object relResult = null; if (relType.Name.ToLower() != "void") { relResult = JsonConvert.DeserializeObject(reObj.Result.JsonValue, relType); } return(relResult); } } finally { if (streamResponse != null) { streamResponse.Close(); } if (response != null) { response.Close(); } } }
public string RequestService <T>(RequestModel requestModel, List <String> lstTbName) { HttpWebResponse response = null; Stream streamResponse = null; try { MethodDC transDataClass = new MethodDC(); transDataClass.ApiConfigKey = requestModel.IServiceName; transDataClass.InterfaceName = requestModel.IServiceName; transDataClass.MethodName = requestModel.MethodName; transDataClass.TypeArguments = requestModel.Types; List <ParameterDC> webParamerList = new List <ParameterDC>(); foreach (object param in requestModel.ParameterList) { ParameterDC aWebParamer = new ParameterDC(); aWebParamer.TypeQualifiedName = param.GetType().AssemblyQualifiedName; aWebParamer.JsonValue = JsonConvert.SerializeObject(param); webParamerList.Add(aWebParamer); } transDataClass.ParameterList = webParamerList; if (lstTbName != null) { foreach (var strName in lstTbName) { foreach (var item in transDataClass.ParameterList) { if (item.TypeQualifiedName.Contains(strName)) { if (item.TypeQualifiedName.Contains(string.Format("HisPlus.Contract.Messages.{0}, HisPlus.Contract, Version=0.0.0.0,", strName))) { item.TypeQualifiedName = item.TypeQualifiedName.Replace(string.Format("HisPlus.Contract.Messages.{0}, HisPlus.Contract, Version=0.0.0.0,", strName), string.Format("Orm.Model.{0}, Orm.Model, Version=1.0.0.0,", strName.Replace("Dto", string.Empty))); } if (item.TypeQualifiedName.Contains(string.Format("HisPlus.Contract.Messages.Generated.{0}, HisPlus.Contract, Version=0.0.0.0,", strName))) { item.TypeQualifiedName = item.TypeQualifiedName.Replace(string.Format("HisPlus.Contract.Messages.Generated.{0}, HisPlus.Contract, Version=0.0.0.0,", strName), string.Format("Orm.Model.{0}, Orm.Model, Version=1.0.0.0,", strName.Replace("Dto", string.Empty))); } } } } } //将要传递的数据序列化成json格式 string jsonContract = JsonConvert.SerializeObject(transDataClass); //TODO:加密或压缩对jsonContract,密文可根据日期变化。服务端验证密文 MethodDC vdf = JsonConvert.DeserializeObject <MethodDC>(jsonContract); //将要传递的json转成byte[] byte[] PostData = Encoding.UTF8.GetBytes(jsonContract); var watch = new System.Diagnostics.Stopwatch(); watch.Start(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestModel.ApiUrl);//http://localhost:6848/Handler.api request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.GetRequestStream().Write(PostData, 0, PostData.Length); request.ContentType = "text/xml; charset=utf-8"; ServicePoint currentServicePoint = request.ServicePoint; currentServicePoint.ConnectionLimit = 1000; response = (HttpWebResponse)request.GetResponse(); streamResponse = response.GetResponseStream(); string strResponse = string.Empty; //如果服务端采用了GZIP压缩,则先解压缩。 if (response.ContentEncoding.ToLower().Contains("gzip")) { using (GZipStream gz = new GZipStream(streamResponse, CompressionMode.Decompress)) { using (StreamReader readerGzip = new StreamReader(gz, Encoding.UTF8)) { strResponse = readerGzip.ReadToEnd(); } } } else { using (StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8)) { strResponse = streamRead.ReadToEnd(); } } //TODO:解密或解压缩对strResponse MethodDC reObj = JsonConvert.DeserializeObject <MethodDC>(strResponse); watch.Stop(); if (reObj.Result.HasException) { throw new Exception("Message: " + reObj.Result.ExceptionMessage + "\r\n" + "Stack: " + reObj.Result.ExceptionStack); } else { return(reObj.Result.JsonValue); } } finally { if (streamResponse != null) { streamResponse.Close(); } if (response != null) { response.Close(); } } }
/// <summary> /// 解析WebApi的请求。 /// </summary> /// <param name="context">http上下文</param> private void ResolveWebApi(HttpContext context) { var watch = new System.Diagnostics.Stopwatch(); watch.Start(); Stream streamResponse = context.Request.InputStream; StreamReader streamRead = new StreamReader(streamResponse, Encoding.UTF8); string strResponse = streamRead.ReadToEnd(); streamResponse.Close(); streamRead.Close(); MethodDC theContract = new MethodDC(); ApiResultDC theResult = new ApiResultDC(); InvokeResult result = new InvokeResult(); try { theContract = Serializer.Deserialize <MethodDC>(strResponse); ApiCore apiCpre = new ApiCore(theContract); result = apiCpre.Invoke(); if (result.ResultType.Name.ToLower() != "void") { theResult.JsonValue = Serializer.Serialize(result.ResultValue); theResult.TypeQualifiedName = result.ResultType.AssemblyQualifiedName; } else { theResult.JsonValue = string.Empty; theResult.TypeQualifiedName = result.ResultType.AssemblyQualifiedName; } } catch (Exception ex) { if (ex.InnerException != null && ex.InnerException is Orm.Utilities.InformationException) { theResult.HasException = true; theResult.ExceptionMessage = ex.InnerException.Message; theResult.ExceptionState = 1; } else if (ex.InnerException is Orm.Utilities.WarningException) { theResult.HasException = true; theResult.ExceptionMessage = ex.InnerException.Message; theResult.ExceptionState = 2; } else if (ex.InnerException is Orm.Utilities.ErrorException) { theResult.HasException = true; theResult.ExceptionMessage = ex.InnerException.Message; theResult.ExceptionState = 2; } else { theResult.HasException = true; theResult.ExceptionMessage = ex.InnerException == null ? ex.Message : ex.InnerException.Message; theResult.ExceptionStack = ex.InnerException == null ? ex.StackTrace : ex.InnerException.StackTrace; } //Orm.Framework.Services.AppLogger.Log(ex.InnerException == null ? ex.Message : ex.InnerException.Message + "\r\n" + ex.StackTrace); StringBuilder errLog = new StringBuilder(); if (strResponse.Length > 500) { errLog.Append(strResponse.Substring(0, 500)); } else { errLog.Append(strResponse); } Orm.Framework.Services.AppLogger.Log(ex.InnerException == null ? "\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.StackTrace + "\r\n\r\n" + errLog.ToString() : "\r\n\r\n" + ex.InnerException.Message + "\r\n\r\n" + ex.InnerException.StackTrace + "\r\n\r\n" + errLog.ToString()); } finally { //Orm.Redis.RedisAudit redis = new Orm.Redis.RedisAudit() { ClientIP = context.Request.UserHostAddress, ServiceName = theContract.InterfaceName, MethodName = theContract.MethodName, RequestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ElapsedTime = watch.ElapsedMilliseconds.ToString(), RequestArguments = JsonConvert.SerializeObject(theContract.ParameterList), Result = JsonConvert.SerializeObject(theResult) }; //TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); //Orm.Redis.RedisHelper.SetAsync(redis.ServiceName + "," + redis.MethodName + "," + redis.ClientIP + "," + redis.RequestTime + "," + Convert.ToInt64(ts.TotalSeconds).ToString(), JsonConvert.SerializeObject(redis), 3 * 60 * 60); } theContract.Result = theResult; string jsonResult = Serializer.Serialize(theContract); context.Response.Write(jsonResult); //如果返回的数据大点则采用GZip压缩。 if (jsonResult.Length > 10000) { //向输出流头部添加压缩信息 context.Response.AppendHeader("Content-encoding", "gzip"); context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress); } watch.Stop(); string Parameters = ""; for (int i = 0; i < theContract.ParameterList.Count; i++) { Parameters += theContract.ParameterList[i].JsonValue + "@"; } CountUserData countUserData = new CountUserData { ApiInterfaceName = theContract.InterfaceName, ClientComputerIP = context.Request.UserHostAddress, //UserName = UserProfiles.UserName, //LocationName = UserProfiles.HospitalName, MethodName = theContract.MethodName, ResponseData = (jsonResult.Length / 1024.00).ToString("f0"), OperTime = context.Timestamp, ParameterContents = Parameters, CounterTime = watch.ElapsedMilliseconds, }; JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); System.Text.StringBuilder data_mainJson = new System.Text.StringBuilder(); jsSerializer.Serialize(countUserData, data_mainJson); string strRequestLog = string.Format("Url:{0} ", data_mainJson); Orm.Framework.Services.AppLogger.Log(strRequestLog, @"E:\PerformanceLog\" + DateTime.Now.ToString("yyyyMMdd"), AppDomain.CurrentDomain.Id.ToString() + ".log"); //写请求日志,用于跟踪请求的时间和数据大小。 if (watch.ElapsedMilliseconds > 2000) { StringBuilder errLog = new StringBuilder(); if (strResponse.Length > 500) { errLog.Append(strResponse.Substring(0, 500)); } else { errLog.Append(strResponse); } string strRequestTimeLog = string.Format("Url:{0} 大于2秒:{1} JSON:{2}", context.Request.Url.ToString(), watch.ElapsedMilliseconds.ToString(), errLog); // Orm.Framework.Services.AppLogger.Log(strRequestTimeLog, @"D:\PerformanceLog\" + DateTime.Now.ToString("yyyyMMdd"), AppDomain.CurrentDomain.Id.ToString() + ".log"); strRequestTimeLog = null; } //如果是大对象85000的10倍 if (System.Text.Encoding.Default.GetByteCount(jsonResult) > 840000) { StringBuilder errLog = new StringBuilder(); if (strResponse.Length > 500) { errLog.Append(strResponse.Substring(0, 500)); } else { errLog.Append(strResponse); } //向输出流头部添加压缩信息 // Orm.Framework.Services.AppLogger.Log(string.Format("Url:{0} 大于850K的对象:{1}", context.Request.Url.ToString(), errLog), @"D:\PerformanceLog\" + DateTime.Now.ToString("yyyyMMdd"), AppDomain.CurrentDomain.Id.ToString() + ".log"); } jsonResult = null; strResponse = null; }
/// <summary> /// 解析WebApi的请求。 /// </summary> /// <param name="context">http上下文</param> private void ResolveWebApiEx(HttpContext context) { HttpRequest request = context.Request; var nameSpace = "Orm.Framework.Common"; //接口所在命名空间 var className = "WebAPI"; //接口类名 var methodName = request.QueryString["action"]; //.Form["action"] //methodName = "UpdateFollowInfo"; Assembly assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + @"bin\" + nameSpace + ".dll"); // 动态调用方法。 object eval = assembly.CreateInstance(nameSpace + "." + className); MethodInfo method = eval.GetType().GetMethod(methodName); MethodDC theContract = new MethodDC(); ApiResultDC theResult = new ApiResultDC(); try { theContract.MethodName = methodName; #region 参数设置 //获取反射方法的参数和参数的类型 Dictionary <string, Type> dicParam = new Dictionary <string, Type>(); ParameterInfo[] paramters = method.GetParameters(); foreach (ParameterInfo item in paramters) { dicParam.Add(item.Name, item.ParameterType); } //参数赋值 List <ParameterDC> paramList = new List <ParameterDC>(); foreach (var item in request.Form.AllKeys) { string paramValue = request.Form[item].ToString(); if (dicParam[item].Name == "String") { paramValue = "\"" + paramValue + "\""; } paramList.Add(new ParameterDC { JsonValue = paramValue, TypeQualifiedName = dicParam[item].FullName }); } //if (paramList.Count > 0) theContract.ParameterList = paramList; //else //{ // var p = new ParameterDC { JsonValue = "344", TypeQualifiedName = typeof(int).FullName }; // var p2 = new ParameterDC { JsonValue = "5", TypeQualifiedName = typeof(int).FullName }; // var p1 = new ParameterDC { JsonValue = "\"更新\"", TypeQualifiedName = typeof(string).FullName }; // var plist = new List<ParameterDC>(); // plist.Add(p); // plist.Add(p2); // plist.Add(p1); // theContract.ParameterList = plist; //} if (paramters.Count() != theContract.ParameterList.Count) { ReturnValue returnValue = new ReturnValue(); returnValue.ErrorCode = -1; returnValue.ErrorMsg = "参数个数不匹配"; var jsonResult = Serializer.Serialize(returnValue); context.Response.Write(jsonResult); return; } #endregion ApiCore apiCpre = new ApiCore(theContract); var result = apiCpre.Invoke(eval); if (result.ResultType.Name.ToLower() != "void") { theResult.JsonValue = Serializer.Serialize(result.ResultValue); theResult.TypeQualifiedName = result.ResultType.AssemblyQualifiedName; context.Response.Write(theResult.JsonValue); //context.Response = theResult.JsonValue; } else { theResult.JsonValue = string.Empty; theResult.TypeQualifiedName = result.ResultType.AssemblyQualifiedName; ReturnValue returnValue = new ReturnValue(); returnValue.ErrorCode = -1; returnValue.ErrorMsg = "此接口方法没有返回值"; var jsonResult = Serializer.Serialize(returnValue); context.Response.Write(jsonResult); return; } } catch (Exception ex) { ReturnValue returnValue = new ReturnValue(); returnValue.ErrorCode = -1; returnValue.ErrorMsg = "接口调用异常:" + ex.Message; var jsonResult = Serializer.Serialize(returnValue); context.Response.Write(jsonResult); } }