Beispiel #1
0
        /// <summary>
        /// 运行方法
        /// </summary>
        /// <returns></returns>
        public InvokeResult Invoke()
        {
            object Result = null;

            object theApi = ServiceTaker.GetServiceByKey(theContract.InterfaceName, theContract.ApiConfigKey);

            List <object> paramList  = GetParamList(theContract);
            var           theType    = theApi.GetType();
            int           generic    = theContract.MethodName.IndexOf("<");
            var           methodName = generic >= 0 ?
                                       theContract.MethodName.Substring(0, generic) : theContract.MethodName;

            var methods = theType.GetMethods().Where(m => m.Name == methodName);


            //如果找不到方法
            if (methods.Count() == 0)
            {
                throw new Exception("找不到目标方法");
            }

            var method = GetMethod(methods, theContract.TypeArguments, paramList);

            if (method == null)
            {
                throw new Exception("未能找到方法名:" + methodName + "接口名称:" + theContract.InterfaceName);
            }
            if (!method.IsPublic)
            {
                throw new Exception("目标方法不是公有的");
            }

            if (method.IsAbstract) //如果是抽象方法。
            {
                throw new Exception("目标方法是抽象方法");
            }

            InvokeResult theRes = new InvokeResult();

            if (generic < 0)
            {
                Result            = method.Invoke(theApi, paramList.ToArray());
                theRes.ResultType = method.ReturnType;
            }
            else
            {
                MethodInfo methodInfo;
                Type[]     types = null;
                if (theContract.TypeArguments != null)
                {
                    types = new Type[theContract.TypeArguments.Length];
                    for (int i = 0; i < theContract.TypeArguments.Length; i++)
                    {
                        types[i] = Type.GetType(theContract.TypeArguments[i]);
                    }
                }
                if (types == null)
                {
                    methodInfo = method.MakeGenericMethod();
                }
                else
                {
                    methodInfo = method.MakeGenericMethod(types);
                }
                Result            = methodInfo.Invoke(theApi, paramList.ToArray());
                theRes.ResultType = methodInfo.ReturnType;
            }
            theRes.ResultValue = Result;
            return(theRes);
        }
Beispiel #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;
        }