Esempio n. 1
0
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private string CallHttp()
        {
            // 当前请求调用的模型对应的主机名称
            string httpHost;

            // 当前请求调用的Api名称
            var httpApi = Data.RouteHost == HostConfig.DefaultHost ? Data.Uri.PathAndQuery : $"{Data.ApiName}{Data.Uri.Query}";

            // 查找主机
            if (Data.RouteHost.Hosts.Length == 1)
            {
                httpHost = Data.RouteHost.Hosts[0];
            }
            else
            {
                lock (Data.RouteHost)
                {
                    //平均分配
                    httpHost = Data.RouteHost.Hosts[Data.RouteHost.Next];
                    if (++Data.RouteHost.Next >= Data.RouteHost.Hosts.Length)
                    {
                        Data.RouteHost.Next = 0;
                    }
                }
            }
            // 远程调用
            var caller = new HttpApiCaller(httpHost)
            {
                Bearer = $"Bearer {ApiContext.RequestContext.Bear}"
            };
            var req = caller.CreateRequest(httpApi, Data.HttpMethod, Request, Data);

            LogRecorder.BeginStepMonitor("内部HTTP调用");
            LogRecorder.MonitorTrace($"Url:{req.RequestUri.PathAndQuery}");
            LogRecorder.MonitorTrace($"Auth:{caller.Bearer}");

            try
            {
                // 远程调用状态
                Data.ResultMessage = caller.GetResult(req, out var webStatus);
                LogRecorder.MonitorTrace(webStatus.ToString());
                if (webStatus != WebExceptionStatus.Success)
                {
                    Data.Status = RouteStatus.RemoteError;
                }
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.MonitorTrace($"发生异常:{ex.Message}");
                Data.ResultMessage = RouteRuntime.NetworkError;
                Data.Status        = RouteStatus.RemoteError;
            }
            finally
            {
                LogRecorder.MonitorTrace(Data.ResultMessage);
                LogRecorder.EndStepMonitor();
            }
            return(Data.ResultMessage);
        }
Esempio n. 2
0
        /// <summary>
        ///     页面操作处理入口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            CurrentPageName = GetFriendPageUrl();
            LogRecorder.BeginMonitor(CurrentPageName);
            LogRecorder.MonitorTrace(Request.Url.AbsolutePath);

            LogRequestInfo();
            try
            {
                ProcessRequest();
            }
            catch (Exception exception)
            {
                LogRecorder.EndStepMonitor();
                LogRecorder.BeginStepMonitor("Exception");
                LogRecorder.MonitorTrace(exception.Message);
                LogRecorder.Exception(exception);
                Debug.WriteLine(exception);
                OnFailed(exception);
                LogRecorder.EndStepMonitor();
            }
            LogRecorder.BeginStepMonitor("Result");
            OnResult();
            LogRecorder.EndStepMonitor();
            LogRecorder.EndMonitor();
        }
Esempio n. 3
0
        private void ProcessRequest()
        {
            LogRecorder.BeginStepMonitor("LoadAuthority");
            var canDo = LoadAuthority();

            LogRecorder.MonitorTrace(canDo.ToString());
            LogRecorder.EndStepMonitor();
            if (!canDo)
            {
                ModelContext.LastMessage = "非法访问";
                return;
            }
            LogRecorder.BeginStepMonitor("Prepare");
            OnPrepare();
            LogRecorder.EndStepMonitor();
            LogRecorder.BeginStepMonitor("CheckCanDo");
            canDo = IsPublicPage || CheckCanDo();
            LogRecorder.MonitorTrace(canDo.ToString());
            LogRecorder.EndStepMonitor();
            if (!canDo)
            {
                return;
            }
            LogRecorder.BeginStepMonitor("OnPageLoaded");
            OnPageLoaded();
            LogRecorder.EndStepMonitor();
        }
Esempio n. 4
0
        /// <summary>
        ///     通过Post调用
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ApiValueResult <string> Post(string apiName, string form)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));

            var ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + form);

            var req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);

            try
            {
                using (var rs = req.GetRequestStream())
                {
                    var formData = Encoding.UTF8.GetBytes(form);
                    rs.Write(formData, 0, formData.Length);
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                LogRecorder.EndStepMonitor();
                return(ApiValueResult <string> .ErrorResult(ErrorCode.NetworkError));
            }

            return(GetResult(req));
        }
Esempio n. 5
0
        /// <summary>
        ///     通过Post调用
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ApiValueResult Post(string apiName, string form)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));
            string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + form);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);
            try
            {
                using (Stream rs = req.GetRequestStream())
                {
                    byte[] formData = Encoding.UTF8.GetBytes(form);
                    rs.Write(formData, 0, formData.Length);
                }
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.EndStepMonitor();
                return(ErrorResult(-3));
            }
            using (MonitorScope.CreateScope("Caller Remote"))
            {
                return(GetResult(req));
            }
        }
Esempio n. 6
0
 /// <summary>
 ///     开始日志监测
 /// </summary>
 /// <param name="data"></param>
 private static void BeginMonitor(RouteData data)
 {
     if (!LogRecorder.LogMonitor)
     {
         return;
     }
     try
     {
         LogRecorder.BeginMonitor(data.Uri.ToString());
         LogRecorder.BeginStepMonitor("HTTP");
         var args = new StringBuilder();
         args.Append("Headers:");
         args.Append(JsonConvert.SerializeObject(data.Headers));
         LogRecorder.MonitorTrace(args.ToString());
         LogRecorder.MonitorTrace($"Method:{data.HttpMethod}");
     }
     catch (Exception e)
     {
         LogRecorder.MonitorTrace(e.Message);
         LogRecorder.Exception(e);
     }
     finally
     {
         LogRecorder.EndStepMonitor();
     }
 }
Esempio n. 7
0
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private string CallZero()
        {
            var values = new Dictionary <string, string>();

            //参数解析
            foreach (var query in Request.Query.Keys)
            {
                if (!values.ContainsKey(query))
                {
                    values.Add(query, Request.Query[query]);
                }
            }

            if (Data.HttpMethod == "POST")
            {
                if (Request.ContentLength > 0)
                {
                    foreach (var form in Request.Form.Keys)
                    {
                        if (!values.ContainsKey(form))
                        {
                            values.Add(form, Request.Form[form]);
                        }
                    }
                }
            }

            LogRecorder.BeginStepMonitor("内部Zero调用");
            LogRecorder.MonitorTrace($"Station:{Data.HostName}");
            LogRecorder.MonitorTrace($"Command:{Data.ApiName}");

            // 远程调用状态
            try
            {
                Data.ResultMessage = StationProgram.Call(Data.HostName, Data.ApiName, JsonConvert.SerializeObject(values));
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.MonitorTrace($"发生异常:{ex.Message}");
                Data.ResultMessage = RouteRuntime.NetworkError;
                Data.Status        = RouteStatus.RemoteError;
            }
            finally
            {
                LogRecorder.MonitorTrace(Data.ResultMessage);
                LogRecorder.EndStepMonitor();
            }

            return(Data.ResultMessage);
        }
Esempio n. 8
0
 /// <summary>
 ///     缓存类型对应的权限用户
 /// </summary>
 public void CacheTypeUser()
 {
     LogRecorder.BeginStepMonitor("CacheEditUser");
     using (SystemContextScope.CreateScope())
     {
         _allPowers = _rpAccess.All();
         using (var proxy = new RedisProxy(RedisProxy.DbAuthority))
         {
             CacheUser(proxy, "edit", edits);
             CacheUser(proxy, "audit", audits);
         }
     }
     LogRecorder.EndStepMonitor();
 }
Esempio n. 9
0
        /// <summary>
        ///     通过Get调用
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="apiName"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public ApiResult <TResult> Get <TResult>(string apiName, string arguments)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));
            string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + arguments);
            if (!string.IsNullOrWhiteSpace(arguments))
            {
                apiName = $"{apiName}?{arguments}";
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "GET";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);
            return(GetResult <TResult>(req));
        }
Esempio n. 10
0
 /// <summary>
 ///     开始时的处理
 /// </summary>
 /// <returns>如果返回内容不为空,直接返回,后续的处理不再继续</returns>
 public static int OnBegin(RouteData data)
 {
     if (!LogRecorder.LogMonitor)
     {
         return(0);
     }
     try
     {
         LogRecorder.BeginMonitor(data.Uri.ToString());
         LogRecorder.BeginStepMonitor("HTTP");
         var args = new StringBuilder();
         args.Append("Headers:");
         foreach (var head in data.Headers)
         {
             args.Append($"【{head.Key}】{head.Value.LinkToString('|')}");
         }
         LogRecorder.MonitorTrace(args.ToString());
         LogRecorder.MonitorTrace($"Method:{data.HttpMethod}");
         if (!string.IsNullOrWhiteSpace(data.QueryString))
         {
             LogRecorder.MonitorTrace($"Query:{data.QueryString}");
         }
         if (!string.IsNullOrWhiteSpace(data.Form))
         {
             LogRecorder.MonitorTrace($"Form:{data.Form}");
         }
         if (!string.IsNullOrWhiteSpace(data.Context))
         {
             LogRecorder.MonitorTrace("Context:" + data.Context);
         }
     }
     catch (Exception e)
     {
         LogRecorder.MonitorTrace(e.Message);
         LogRecorder.Exception(e);
     }
     finally
     {
         LogRecorder.EndStepMonitor();
     }
     return(0);
 }
Esempio n. 11
0
 /// <summary>
 ///     开始日志监测
 /// </summary>
 /// <param name="data"></param>
 private static void BeginMonitor(RouteData data)
 {
     if (!LogRecorder.LogMonitor)
     {
         return;
     }
     try
     {
         LogRecorder.BeginMonitor(data.Uri.ToString());
         LogRecorder.BeginStepMonitor("HTTP");
         var args = new StringBuilder();
         args.Append("Headers:");
         args.Append(JsonConvert.SerializeObject(data.Headers));
         LogRecorder.MonitorTrace(args.ToString());
         LogRecorder.MonitorTrace($"Method:{data.HttpMethod}");
         if (!string.IsNullOrWhiteSpace(data.QueryString))
         {
             LogRecorder.MonitorTrace($"Query:{data.QueryString}");
         }
         if (!string.IsNullOrWhiteSpace(data.Form))
         {
             LogRecorder.MonitorTrace($"Form:{data.Form}");
         }
         if (!string.IsNullOrWhiteSpace(data.Context))
         {
             LogRecorder.MonitorTrace("Context:" + data.Context);
         }
     }
     catch (Exception e)
     {
         LogRecorder.MonitorTrace(e.Message);
         LogRecorder.Exception(e);
     }
     finally
     {
         LogRecorder.EndStepMonitor();
     }
 }
Esempio n. 12
0
        /// <summary>
        /// 生成请求对象
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="method"></param>
        /// <param name="arg"></param>
        /// <returns></returns>
        HttpWebRequest CreateRequest(string apiName, string method, string arg)
        {
            var auth = $"Bearer {Bearer}";

            var url = $"{Host?.TrimEnd('/') + "/"}{apiName?.TrimStart('/')}";

            if (method == "GET" && !string.IsNullOrWhiteSpace(arg))
            {
                url = $"{url}?{arg}";
            }

            LogRecorder.BeginStepMonitor($"内部API调用:{apiName}");
            LogRecorder.MonitorTrace($"Url:{url}");
            LogRecorder.MonitorTrace($"Auth:{auth}");

            var req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = method;
            //req.Headers.Add(HttpRequestHeader.UserAgent, "Yizuan.Service.WebApi.WebApiCaller");
            req.Headers.Add(HttpRequestHeader.Authorization, auth);

            if (method == "POST")
            {
                if (arg == null)
                {
                    arg = "";
                }
                req.ContentType = "application/x-www-form-urlencoded";
                using (var rs = req.GetRequestStream())
                {
                    var formData = Encoding.UTF8.GetBytes(arg);
                    rs.Write(formData, 0, formData.Length);
                }
                LogRecorder.MonitorTrace("Form:" + arg);
            }
            return(req);
        }
Esempio n. 13
0
        /// <summary>
        /// 调用
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static void CallTask(HttpContext context)
        {
            var uri = context.Request.GetUri();

            try
            {
                HttpProtocol.FormatResponse(context.Response);
                //内容页转向
                if (uri.LocalPath.IndexOf(".", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    context.Response.Redirect(AppConfig.Config.SystemConfig.ContextHost + uri.LocalPath.Trim('/'));
                    return;
                }
                //跨域支持
                if (context.Request.Method.ToUpper() == "OPTIONS")
                {
                    HttpProtocol.Cros(context.Response);
                    return;
                }
                //命令
                if (RouteCommand.InnerCommand(uri.LocalPath, context.Response))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e);
                RuntimeWaring.Waring("Route", uri.LocalPath, e.Message);
                context.Response.WriteAsync(RouteRuntime.InnerError, Encoding.UTF8);
                return;
            }

            var router = new HttpRouter(context);

            HttpIoLog.OnBegin(router.Data);
            var counter = PerformanceCounter.OnBegin(router.Data);

            try
            {
                var checker = new SecurityChecker
                {
                    Request = context.Request
                };
                if (!checker.PreCheck())
                {
                    router.Data.Status = RouteStatus.DenyAccess;
                    context.Response.WriteAsync(RouteRuntime.Inner2Error, Encoding.UTF8);
                }
                else
                {
                    // 正常调用
                    router.Call();
                    LogRecorder.BeginStepMonitor("End");
                    // 写入返回
                    router.WriteResult();
                    // 缓存
                    RouteChahe.CacheResult(router.Data);
                }
            }
            catch (Exception e)
            {
                router.Data.Status = RouteStatus.LocalError;
                LogRecorder.Exception(e);
                RuntimeWaring.Waring("Route", uri.LocalPath, e.Message);
                context.Response.WriteAsync(RouteRuntime.InnerError, Encoding.UTF8);
            }
            finally
            {
                //计时
                counter.End(router.Data);
                HttpIoLog.OnEnd(router.Data);
            }
        }