示例#1
0
        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();
                }
            }
        }
示例#2
0
        /// <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;
        }