/// <summary> /// 准备 /// </summary> /// <param name="service">当前服务</param> /// <param name="message">当前消息</param> /// <param name="tag">扩展信息</param> /// <returns></returns> Task <bool> IMessageMiddleware.Prepare(IService service, IInlineMessage message, object tag) { if (!string.Equals(service.ServiceName, message.Service, StringComparison.OrdinalIgnoreCase)) { return(Task.FromResult(true)); } Service = service; Message = message; Tag = tag; action = Service.GetApiAction(Message.Method); //1 查找调用方法 if (action == null) { FlowTracer.MonitorDetails(() => $"错误: 接口({Message.Method})不存在"); Message.State = MessageState.Unhandled; Message.ResultCreater = ApiResultHelper.State; scope = MessageHandleScope.None; } else { FlowTracer.MonitorTrace($"[Action] {action.Info.ControllerName}.{action.Info.Name}"); } return(Task.FromResult(true)); }
internal ApiResult <TResult> Execute <TResult>(IApiAction <TResult> apiAction) where TResult : class { var request = new RestRequest("", apiAction.RequestMethod); request.AddParameter("action", apiAction.Action); var parameters = apiAction.BuildParameterList(); foreach (var pair in parameters) { request.AddParameter(pair.Key, pair.Value); } var response = _client.Execute(request); var json = JsonObject.Parse(response.Content); var actionJson = json.Object(apiAction.Action); var result = new ApiResult <TResult> { Result = apiAction.BuildResult(actionJson), Response = response, }; return(result); }
/// <summary> /// 检查接口是否可执行 /// </summary> /// <param name="action"></param> /// <param name="message"></param> /// <returns></returns> public bool Check(IApiAction action, IInlineMessage message) { var user = GlobalContext.User; //1 确定调用方法及对应权限 if (ZeroAppOption.Instance.IsOpenAccess || action.Option.HasFlag(ApiOption.Anymouse)) { return(true); } if (!int.TryParse(user[ZeroTeamJwtClaim.Exp], out int last) || DateTime.Now.ToTimestamp() > last) { FlowTracer.MonitorInfomation(() => $"令牌已过期 => {new DateTime(1970, 1, 1).AddSeconds(last)}"); message.State = MessageState.Deny; message.Result = ApiResultHelper.TokenTimeOutJson; return(false); } //1 确定调用方法及对应权限 if (UserInfo.IsLoginUser(user)) { return(true); } FlowTracer.MonitorInfomation("错误: 需要用户登录信息"); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.BusinessException; status.Message = "拒绝访问"; message.RealState = MessageState.Deny; message.ResultData = status; return(false); }
public void ProcessRequest(HttpContext context) { context.Response.CacheControl = "no-cache"; context.Response.AddHeader("Pragma", "no-cache"); context.Response.ContentType = "text/plain"; Hashtable ht = new Hashtable(); try { ht = GetRequestParams(context); if (ht.Keys.Count > 0) { if (ht["action"] == null || ht["action"].ToString().Trim().Length <= 0) { throw new Exception("参数不完整"); } if (ht["sign"] == null || ht["sign"].ToString().Trim().Length <= 0) { throw new Exception("参数不完整"); } Hashtable appht = LoadAclList(); string client_id = ht["client_id"].ToString(); if (VeryfySign(ht, appht[client_id].ToString())) { string actionName = ht["action"].ToString(); Assembly assembly = Assembly.GetExecutingAssembly(); object obj = assembly.CreateInstance("YR.Web.api.baojia.service." + actionName); IApiAction action = (IApiAction)obj; //调用相对应的接口方法 ApiResp result = action.Execute(ht); context.Response.Write(JsonConvert.SerializeObject(result)); Logger.Info("宝驾互通接口调用(成功),访问ip:" + context.Request.UserHostAddress + ",参数:" + JsonConvert.SerializeObject(ht) + ",返回值:" + result); } else { throw new Exception("参数校验失败"); } } else { throw new Exception("数据为空"); } } catch (Exception e) { ApiResp resp = new ApiResp(); resp.code = "-1"; resp.msg = "系统异常," + e.Message; context.Response.Write(JsonConvert.SerializeObject(resp)); Logger.Error("宝驾互通接口调用(失败),访问ip:" + context.Request.UserHostAddress + ",参数:" + JsonConvert.SerializeObject(ht) + ",异常:" + e.Message); } }
public async Task <TResult> Execute <TResult>(IApiAction <TResult> action) { if (_client == null) { Initialize(); } return(await action.DoAsync(this)); }
public void ProcessRequest(HttpContext context) { context.Response.CacheControl = "no-cache"; context.Response.AddHeader("Pragma", "no-cache"); context.Response.ContentType = "text/plain"; string clientData = ""; try { if (context.Request.HttpMethod.ToLower() != "post") { throw new Exception("调用方式错误"); } var reader = new System.IO.StreamReader(context.Request.InputStream); clientData = reader.ReadToEnd(); reader.Close(); if (!string.IsNullOrEmpty(clientData)) { clientData = clientData.Trim(); string cmd = ""; dynamic jsonObj = DynamicJson.Parse(clientData); if (jsonObj.IsDefined("cmd")) { cmd = jsonObj.cmd; } Assembly assembly = Assembly.GetExecutingAssembly(); string typeName = cmd.Substring(0, 1).ToUpper() + cmd.Substring(1, cmd.Length - 1) + "Action"; object obj = assembly.CreateInstance("YR.Web.api.xacloud.service." + typeName); IApiAction action = (IApiAction)obj; //调用相对应的接口方法 Hashtable args_ht = new Hashtable(); args_ht["json"] = clientData; ApiResp result = action.Execute(args_ht); Logger.Info("小安盒子接口网关上报数据," + result.Code + ",访问ip:" + context.Request.UserHostAddress + ",参数:" + clientData + ",返回值:" + JsonConvert.SerializeObject(result)); context.Response.Write(JsonConvert.SerializeObject(result)); } else { Logger.Error("小安盒子接口网关上报数据失败,请求参数为空"); throw new Exception("请求参数为空"); } } catch (Exception e) { ApiResp result = new ApiResp(); result.Code = "-1"; result.Message = e.Message; Logger.Error("小安盒子接口网关上报数据失败,访问ip:" + context.Request.UserHostAddress + ",参数:" + clientData + ",异常:" + e); context.Response.Write(JsonConvert.SerializeObject(result)); } }
public void ProcessRequest(HttpContext context) { context.Response.CacheControl = "no-cache"; context.Response.AddHeader("Pragma", "no-cache"); context.Response.ContentType = "text/plain"; string clientData = ""; try { if (context.Request.HttpMethod.ToLower() != "post") { throw new Exception("调用方式错误"); } var reader = new System.IO.StreamReader(context.Request.InputStream); clientData = reader.ReadToEnd(); reader.Close(); if (!string.IsNullOrEmpty(clientData)) { Assembly assembly = Assembly.GetExecutingAssembly(); string typeName = "StatusAction"; object obj = assembly.CreateInstance("YR.Web.api.ydcloud.service." + typeName); IApiAction action = (IApiAction)obj; //if (action == null) // return; //调用相对应的接口方法 Hashtable args_ht = new Hashtable(); args_ht["json"] = clientData; ApiResp result = action.Execute(args_ht); Logger.Info("一动盒子接口网关上报数据(成功),访问ip:" + context.Request.UserHostAddress + ",参数:" + clientData + ",返回值:" + result); } else { throw new Exception("请求参数为空"); } } catch (Exception e) { Logger.Error("一动盒子接口网关上报数据(失败),访问ip:" + context.Request.UserHostAddress + ",参数:" + clientData + ",异常:" + e.Message); } }
/// <summary> /// 参数校验 /// </summary> /// <param name="action"></param> /// <returns></returns> private bool ArgumentPrepare(IApiAction action) { try { action.RestoreArgument(Message); } catch (Exception ex) { var msg = $"错误 : 还原参数异常{ex.Message}"; FlowTracer.MonitorInfomation(msg); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.BusinessException; status.Message = msg; Message.ResultData = status; Message.RealState = MessageState.FormalError; return(false); } try { if (action.ValidateArgument(Message, out var status)) { return(true); } var msg = $"参数校验失败 : {status.Message}"; FlowTracer.MonitorInfomation(msg); Message.ResultData = status; Message.Result = SmartSerializer.ToInnerString(status); Message.RealState = MessageState.FormalError; return(false); } catch (Exception ex) { var msg = $"错误 : 参数校验异常{ex.Message}"; FlowTracer.MonitorInfomation(msg); var status = DependencyHelper.GetService <IOperatorStatus>(); status.Code = OperatorStatusCode.ArgumentError; status.Message = msg; Message.ResultData = status; Message.RealState = MessageState.FormalError; return(false); } }
public async Task <ApiActionResponse> ExecuteAsync(IApiAction apiAction, CancellationToken cancellationToken) { // ReSharper disable once ForCanBeConvertedToForeach - array indexing is faster for (var x = 0; x < PreExecutionTasks.Length; x++) { await PreExecutionTasks[x](apiAction, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); if (apiAction.ActionResponse != null) { return(apiAction.ActionResponse); } } // ExecuteAsync var response = await apiAction.ExecuteAsync(cancellationToken) ?? apiAction.ActionResponse; cancellationToken.ThrowIfCancellationRequested(); return(response ?? apiAction.ActionResponse ?? NoContentResponse.Singleton); }
public void ProcessRequest(HttpContext context) { context.Response.CacheControl = "no-cache"; context.Response.AddHeader("Pragma", "no-cache"); context.Response.ContentType = "text/plain"; Hashtable clientData = new Hashtable(); string cmd = null; try { if (context.Request.HttpMethod.ToLower() != "post") { throw new Exception("调用方式错误"); } clientData = GetRequestData(context); if (clientData != null && clientData.Keys.Count > 0) { if (!ZCloudSignUtil.verify(ZCloudCore.hashtableToDictionary(clientData), ZCloudConfig.md5_key)) { throw new Exception("验签失败"); } if (clientData["cmd"] != null) { cmd = clientData["cmd"].ToString(); } if (string.IsNullOrEmpty(cmd)) { throw new Exception("收到网关发来的通知,但是没有找到命令字"); } Assembly assembly = Assembly.GetExecutingAssembly(); string typeName = cmd.Substring(0, 1).ToUpper() + cmd.Substring(1, cmd.Length - 1) + "Action"; object obj = assembly.CreateInstance("YR.Web.api.zcloud.service." + typeName); IApiAction action = (IApiAction)obj; //if (action == null) // return; //调用相对应的接口方法 ApiResp result = action.Execute(clientData); if (!Not_Response_Cmd.Contains(cmd)) { Hashtable result_ht = new Hashtable(); result_ht.Add("rtCode", "0"); string sign = ZCloudSignUtil.getSign(ZCloudCore.hashtableToDictionary(result_ht), ZCloudConfig.md5_key); result_ht.Add("sign", sign); context.Response.Write(JsonConvert.SerializeObject(result_ht)); } Logger.Info("自由box接口网关上报数据(成功),访问ip:" + context.Request.UserHostAddress + ",参数:" + JsonConvert.SerializeObject(clientData) + ",返回值:" + result); } else { throw new Exception("请求参数为空"); } } catch (Exception e) { if (!Not_Response_Cmd.Contains(cmd)) { Hashtable result_ht = new Hashtable(); result_ht.Add("rtCode", "1"); string sign = ZCloudSignUtil.getSign(ZCloudCore.hashtableToDictionary(result_ht), ZCloudConfig.md5_key); result_ht.Add("sign", sign); context.Response.Write(JsonConvert.SerializeObject(result_ht)); } Logger.Error("自由box接口网关上报数据(失败),访问ip:" + context.Request.UserHostAddress + ",参数:" + JsonConvert.SerializeObject(clientData) + ",异常:" + e.Message); } }
private static Task ValidateModelAsync(IApiAction apiAction, CancellationToken cancellationToken) { return(apiAction.ValidateModelAsync(cancellationToken)); }
protected static Task AuthorizeDataAsync(IApiAction apiAction, CancellationToken cancellationToken) { return(apiAction.AuthorizeDataAsync(cancellationToken)); }
protected static Task PreloadDataAsync(IApiAction apiAction, CancellationToken cancellationToken) { return(apiAction.PreloadDataAsync(cancellationToken)); }