private static void SaveInfo(IBaseRequest request, TypeFineContext ctx, RequestType type, bool save = false) { ctx.RequestInfos.Add(new RequestInfo { RequestType = type, AccountId = request.AccountId, DeviceId = request.DeviceId }); if (save) { ctx.SaveChanges(); } }
/// <summary> /// 发送请求 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="request"></param> /// <returns></returns> public override T Send <T>(IBaseRequest <T> request) { HttpClient httpClient = new HttpClient(); HttpRequestMessage requestMsg = SetHttpRequest(httpClient, request); try { string content = httpClient.SendAsync(requestMsg).Result.Content.ReadAsStringAsync().Result; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(content); XmlNode xmlNode = xmlDoc.FirstChild;//获取到根节点<xml> XmlNodeList nodes = xmlNode.ChildNodes; T response = new T(); var pros = response.GetType().GetProperties(); foreach (XmlNode xn in nodes) { foreach (var pro in pros) { if (xn.Name == pro.Name) { if (pro.GetType() == typeof(int)) { pro.SetValue(response, Convert.ToInt32(xn.InnerText)); } else { pro.SetValue(response, xn.InnerText); } break; } } } return(response); } catch (Exception e) { //记录日志 e return(default(T)); } }
protected Result Validate(IBaseRequest request) { this.logger.LogTrace("Validating the query : {@query} ", request); var validationResult = this.GetValidationResult(request); if (validationResult == null || validationResult.IsValid) { return(Result.Ok()); } validationResult.AddToModelState(this.ModelState, null); this.logger.LogWarning("Validation Errors found: {modelState}", this.ModelState); return(Result.Failure("Validation errors found")); }
public static async Task LogGraphServiceRequest(IDialogContext context, IBaseRequest request, object payload = null) { if (doLogging) { if (request.Method == "POST" || request.Method == "PATCH") { string prettyPayload = JsonConvert.SerializeObject(payload, Formatting.Indented); await context.PostAsync($"```\n{request.Method} {request.RequestUrl}\n\n{prettyPayload}\n```"); } else { await context.PostAsync($"`{request.Method} {request.RequestUrl}`"); } } }
/// <summary> /// Sends the request asynchronously. /// </summary> /// <typeparam name="T"><see cref="Type" /> of the content present in the response.</typeparam> /// <param name="client">The client.</param> /// <param name="request">The request.</param> /// <param name="requestType">Type of the request.</param> /// <param name="tenant">The tenant.</param> /// <param name="scenarioId">The scenario identifier.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The <see cref="Task" /> returning the generic type. /// </returns> public static async Task <T> SendAsync <T>( this IGraphClient client, IBaseRequest request, RequestType requestType, string tenant, Guid scenarioId, CancellationToken cancellationToken = default(CancellationToken)) where T : class { var graphRequest = CreateGraphRequest(request, requestType); var graphResponse = await client .SendAsync <object, T>(graphRequest, tenant, scenarioId, cancellationToken) .ConfigureAwait(false); return(graphResponse.Content); }
public override HttpContent SetHttpContent <T>(IBaseRequest <T> request) { var pros = request.GetType().GetProperties(); Dictionary <string, object> dictionary = new Dictionary <string, object>(); foreach (var item in pros) { dictionary.Add(item.Name, item.GetValue(request)); } var para = dictionary.Select(str => $"{str.Key}={str.Value}"); var content = string.Join("&", para); return(new StringContent(content)); }
public TResponse Excute <TResponse>(IBaseRequest <TResponse> request) where TResponse : IBaseResponse, new() { var sortedMap = new SortedDictionary <string, object>(new SortLowerComparer()); sortedMap.Add("version", Version); sortedMap.Add("method", request.Method); sortedMap.Add("timestamp", Timestamp); sortedMap.Add("nonce", Nonce); sortedMap.Add("partnerId", Config.PartnerId); sortedMap.Add("accesskey", Config.Accesskey); string data = JsonConvert.SerializeObject(request, Formatting.None, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); sortedMap.Add("data", data); string signature = GetSignature(sortedMap); sortedMap.Add("signature", signature); string json = JsonConvert.SerializeObject(sortedMap); var httpRequestModel = new RequestModel(HttpVerbs.POST); httpRequestModel.Url = Url; httpRequestModel.Data = json; httpRequestModel.ContentType = "application/json; charset=utf-8"; httpRequestModel.Accept = "application/json"; httpRequestModel.Encode = Encoding.UTF8; try { var content = HttpUtility.PostHtml(httpRequestModel); if (request.Method == "hotel.order.booking" || request.Method == "hotel.order.cancel") { logWriter.Write("请求参数:{0} \n响应参数:{1}", json, content); } var response = JsonConvert.DeserializeObject <TResponse>(content); return(response); } catch (Exception ex) { logWriter.Write("请求参数:{ 0} \n异常信息:{ 1}", json, ex.ToString()); throw ex; } }
/// <summary> /// Type agnostic extension method that takes in a handler for the response. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="request">Request to send out</param> /// <param name="responseHandler">Handler for the response</param> /// <returns></returns> public static void SendGet <T>(this IBaseRequest request, ResponseHandler responseHandler) { request.Client.HttpProvider.SendAsync(request.GetHttpRequestMessage()). ContinueWith(t => { if (t.IsCompleted) { HttpResponseMessage httpResponse = t.Result; responseHandler.HandleResponse <T>(httpResponse).ConfigureAwait(false); } else if (t.IsFaulted) { Console.WriteLine($"Task failed to send out {request.GetHttpRequestMessage().ToString()}"); Console.WriteLine(t.Exception.Message); } }); }
/// <summary> /// Adds a <see cref="IBaseRequest"/> to batch request content /// </summary> /// <param name="request">A <see cref="BaseRequest"/> to use to build a <see cref="BatchRequestStep"/> to add.</param> /// <returns>The requestId of the newly created <see cref="BatchRequestStep"/></returns> public string AddBatchRequestStep(IBaseRequest request) { if (BatchRequestSteps.Count >= CoreConstants.BatchRequest.MaxNumberOfRequests) { throw new ClientException(new Error { Code = ErrorConstants.Codes.MaximumValueExceeded, Message = string.Format(ErrorConstants.Messages.MaximumValueExceeded, "Number of batch request steps", CoreConstants.BatchRequest.MaxNumberOfRequests) }); } string requestId = Guid.NewGuid().ToString(); BatchRequestStep batchRequestStep = new BatchRequestStep(requestId, request.GetHttpRequestMessage()); (BatchRequestSteps as IDictionary <string, BatchRequestStep>).Add(batchRequestStep.RequestId, batchRequestStep); return(requestId); }
public override T Send <T>(IBaseRequest <T> request) { HttpClient httpClient = new HttpClient(); HttpRequestMessage requestMsg = SetHttpRequest(httpClient, request); try { string json = httpClient.SendAsync(requestMsg).Result.Content.ReadAsStringAsync().Result; var response = JsonConvert.DeserializeObject <T>(json); return(response); } catch (Exception e) { //记录日志 e return(default(T)); } }
public BaseResponse Exec <T>(IBaseRequest <T> request) where T : BaseResponse, new() { //拼接成URL string txtParams = GetParams(request); string url = this.Url + (string.IsNullOrWhiteSpace(request.Action) ? "bops.do" : request.Action);// + "?_locale=zh_CN"; string result = ""; string exception = ""; try { //请求 result = Request.Post(url, txtParams, System.Net.SecurityProtocolType.Tls12); if (XmlHelper.IsXml(result)) { //把返回的内容序列化成对象 var response = XmlHelper.XmlDeserialize <T>(result); return(response); } else { var t = new T(); t.Head.ResMsg = result; return(t); } } catch (Exception ex) { exception = ex.Message; } finally { logger.Trace("(普通请求)请求地址:" + this.Url + ",内容:" + txtParams + ",返回:" + result + ",http异常:" + exception); } return(new T()); }
public BaseResponse Exec <T>(IBaseRequest <T> request) where T : BaseResponse, new() { //拼接成URL string url = request.GetUrl(); string txtParams = GetParam(request); string result = ""; string exception = ""; try { //请求 result = Request.Post(url, txtParams); //把返回的内容序列化成对象 var response = JsonHelper.Deserialize <T>(result); if (response.isRet) { if (IsVerify(JsonHelper.Deserialize <Dictionary <string, string> >(result))) { return(response); } } else { return(response); } } catch (Exception ex) { exception = ex.Message; } finally { logger.Trace("(普通请求)请求地址:" + url + ",内容:" + txtParams + ",返回:" + result + ",http异常:" + exception); } return(new T()); }
public static void MapParams(this IBaseRequest request, Dictionary <string, object> parameters) { if (parameters.Count == 0) { return; } PropertyInfo[] myProperties = request.GetType().GetProperties(); foreach (KeyValuePair <string, object> keyValuePair in parameters) { PropertyInfo myProperty = myProperties.FirstOrDefault(x => x.Name == keyValuePair.Key); if (myProperty == null) { continue; } myProperty.SetValue(request, keyValuePair.Value); } }
/// <summary> /// Add a request to be queued in parallel. /// </summary> /// <typeparam name="T">Object return type</typeparam> /// <param name="request">Request to be sent out</param> /// <param name="handlerFunc">Handler for the response.</param> public void AddRequest <T>(IBaseRequest request, Action <T> handlerFunc) { HttpRequestMessage httpRequestMessage = request.GetHttpRequestMessage(); Task task = SendMessageAsyncTask <T>(httpRequestMessage). ContinueWith(t => { if (t.IsCompleted) { handlerFunc(t.Result); } else if (t.IsFaulted) { Console.WriteLine($"Task failed to send out {httpRequestMessage.ToString()}"); Console.WriteLine(t.Exception.Message); } }); _taskCollection.Add(task); }
public async Task <ValidatorResult> Validate(IBaseRequest request) { if (request is IGameRequest) { var result = await gameRequestValidator.Validate(request as IGameRequest); if (!result.IsSuccessful) { return(new ValidatorResult(result.Error)); } } if (request is IGameRoundRequest) { var result = await gameRoundRequestValidator.Validate(request as IGameRoundRequest); if (!result.IsSuccessful) { return(new ValidatorResult(result.Error)); } } if (request is IUserRequest) { var result = await userRequestValidator.Validate(request as IUserRequest); if (!result.IsSuccessful) { return(new ValidatorResult(result.Error)); } } if (request is IPlayerRequest) { var result = await playerRequestValidator.Validate(request as IPlayerRequest); if (!result.IsSuccessful) { return(new ValidatorResult(result.Error)); } } return(new ValidatorResult()); }
public override HttpRequestMessage SetHttpRequest <T>(HttpClient client, IBaseRequest <T> request) { if (request.GetHttpMethod() == HttpMethod.Get) { string para = SetHttpContent(request).ReadAsStringAsync().Result; HttpRequestMessage requestMsg = new HttpRequestMessage(request.GetHttpMethod(), DoMain + "?" + para); return(requestMsg); } else { HttpRequestMessage requestMsg = new HttpRequestMessage(request.GetHttpMethod(), DoMain); requestMsg.Content = SetHttpContent(request); return(requestMsg); } }
public BatchPart AddToBatch(IBaseRequest requestItem, Method method, int id = -1, object body = null, BatchPart[] dependsOn = null) { int batchId; if (id == -1) { if (batchRequestItems.Count() == 0) { batchId = 1; } else { batchId = batchRequestItems.Count() + 1; } } else { batchId = id; } var batchUrl = requestItem.RequestUrl.Replace(":443", ""); batchUrl = batchUrl.Replace(requestItem.Client.BaseUrl, ""); int[] dependsOnIds = null; if (dependsOn != null) { dependsOnIds = dependsOn.Select(i => i.id).ToArray(); } BatchPart request = new BatchPart(batchId, batchUrl, method.ToString(), body, dependsOnIds); request.requestItem = requestItem; batchRequestItems = batchRequestItems.Concat(new List <BatchPart> { request }); return(request); }
public string GetParam <T>(IBaseRequest <T> request) where T : BaseResponse { string signContent = ""; string postContent = ""; Dictionary <string, string> postParams = request.GetParameters(); foreach (var m in postParams.Where(t => !string.IsNullOrWhiteSpace(t.Value)).OrderBy(t => t.Key)) { signContent += "&" + m.Key + "=" + m.Value; postContent += "&" + m.Key + "=" + m.Value; } signContent = signContent.Substring(1); postContent = postContent.Substring(1); var sign = Framework.Security.RSAHelper.SHA1WithRSA(signContent, PingAnConfig.privateKey); postContent += "&sign=" + sign; return(postContent); }
public string GetParams <T>(IBaseRequest <T> request) where T : BaseResponse { string reqTime = DateTime.Now.ToLongDate(); Dictionary <string, string> dicBody = request.GetBody(); dicBody.Add("ReqJnlNo", request.Head.ReqJnlNo); dicBody.Add("ReqTime", reqTime); dicBody.Add("UserId", this.UserId); dicBody.Add("ReqId", request.Method); string signContent = ""; string postContent = ""; foreach (var m in dicBody.OrderBy(t => t.Key)) { signContent += "&" + m.Key + "=" + m.Value; if (m.Key.Equals("IdCardFront", StringComparison.CurrentCultureIgnoreCase) || m.Key.Equals("IdCardBehind", StringComparison.CurrentCultureIgnoreCase)) { postContent += "&" + m.Key + "=" + HttpUtility.UrlEncode(m.Value); } else { postContent += "&" + m.Key + "=" + m.Value; } } signContent = signContent.Substring(1); postContent = postContent.Substring(1); var sortSignContent = request.Sort(signContent); string sign = Sign(sortSignContent); return(postContent + "&Sign=" + sign); }
/// <summary> /// 设置请求报文 /// </summary> /// <typeparam name="T">响应模型</typeparam> /// <param name="request">请求模型</param> /// <returns></returns> public override HttpContent SetHttpContent <T>(IBaseRequest <T> request) { var pros = request.GetType().GetProperties(); Dictionary <string, object> dictionary = new Dictionary <string, object>(); dictionary.Add("app_id", HttpUtility.UrlEncode(AppId, request.GetEncoding())); dictionary.Add("method", HttpUtility.UrlEncode(request.Url(), request.GetEncoding())); dictionary.Add("charset", HttpUtility.UrlEncode(Charset, request.GetEncoding())); dictionary.Add("sign_type", HttpUtility.UrlEncode(Sign_type, request.GetEncoding())); dictionary.Add("timestamp", HttpUtility.UrlEncode(Timestamp, request.GetEncoding())); dictionary.Add("version", HttpUtility.UrlEncode(Version, request.GetEncoding())); if (Return_url != null && Return_url.Length > 0) { dictionary.Add("return_url", HttpUtility.UrlEncode(Return_url, request.GetEncoding())); } if (ReturnUrl != null && ReturnUrl.Length > 0) { dictionary.Add("notify_url", HttpUtility.UrlEncode(ReturnUrl, request.GetEncoding())); } var jsonContent = JsonConvert.SerializeObject(request); dictionary.Add("biz_content", HttpUtility.UrlEncode(jsonContent, request.GetEncoding())); dictionary.Add("sign", HttpUtility.UrlEncode(Sign(request), request.GetEncoding())); var returnDictionary = dictionary.OrderBy(item => item.Key); var para = returnDictionary.Select(str => $"{str.Key}={str.Value}"); var content = string.Join("&", para); StringContent stringContent = new StringContent(content, request.GetEncoding()); stringContent.Headers.ContentType.MediaType = request.GetContentType(); return(stringContent); }
protected async Task <ActionResult> ValidateAndExecute(IBaseRequest command, Func <IBaseRequest, Task <Result> > execute) { this.logger.LogTrace("Validating the command : {@request} ", command); var validationResult = this.GetValidationResult(command); if (validationResult != null && !validationResult.IsValid) { this.logger.LogWarning("Command has validation errors : {@Errors} ", validationResult.Errors); validationResult.AddToModelState(this.ModelState, null); return(this.BadRequest(this.ModelState)); } var result = await execute(command).ConfigureAwait(false); if (result.IsFailure) { this.logger.LogWarning("Command failed with error : {@error} ", result.Error); return(this.BadRequest(result.Error)); } this.logger.LogTrace("Command executed successfully"); return(this.Ok()); }
public string GetParam <T>(IBaseRequest <T> request) where T : BaseResponse { string signString = "", postString = ""; Dictionary <string, string> bizData = request.GetParameters(); bizData.Add("cusid", cusid); bizData.Add("key", key); bizData.Add("appid", appid); foreach (var m in bizData.Where(t => !string.IsNullOrWhiteSpace(t.Value)).OrderBy(t => t.Key)) { signString += "&" + m.Key + "=" + m.Value; if (m.Key != "key") { postString += "&" + m.Key + "=" + m.Value; } } string sign = Framework.Security.Crypt.MD5(signString.Substring(1)); return(postString.Substring(1) + "&sign=" + sign); }
private RestRequest PrepareRequest(IBaseRequest dto) { var request = new RestRequest(dto.Resource); if (dto.HasSegmentOnResource) { foreach (var segment in dto.Segments) { request.AddUrlSegment(segment.Key, segment.Value); } } foreach (var header in dto.Headers) { request.AddHeader(header.Key, header.Value); } foreach (var parameter in dto.Parameters) { request.AddOrUpdateParameter(parameter.Key, parameter.Value); } return(request); }
public ExceptionNotification(Exception exception, IBaseRequest request, DateTime stamp) { Exception = exception; Request = request; Stamp = stamp; }
public override T AsyncSend <T>(IBaseRequest <T> request) { throw new NotImplementedException(); }
public static TCommand ConvertRequestToCommand <TCommand>(this IMapper mapper, IBaseRequest request) where TCommand : class, ICommand { return((TCommand)mapper.Map(request, request.GetType(), typeof(TCommand))); }
private void UpdateUrlPrefix(IBaseRequest service) { if (service != null) { service.UrlPrefix = AppSettings.ServerlUrl; } }
public abstract HttpRequestMessage SetHttpRequest <T>(HttpClient client, IBaseRequest <T> request) where T : IBaseResponse, new();
public abstract string Sign <T>(IBaseRequest <T> request) where T : IBaseResponse, new();
public async Task <ISolutionsResult> GetSolutions( IBaseRequest request, bool fullRecord = true) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var result = new SolutionsResult(); try { var response = await solutionsRepository.GetAll(fullRecord); if (response.Success) { if (request.Paginator != null) { if (StaticDataHelpers.IsPageValid(request.Paginator, response.Objects)) { if (request.Paginator.SortBy == SortValue.NULL) { result.Solutions = response.Objects.ConvertAll(s => (ISudokuSolution)s); } else if (request.Paginator.SortBy == SortValue.ID) { if (!request.Paginator.OrderByDescending) { foreach (var obj in response.Objects) { result.Solutions.Add((ISudokuSolution)obj); } result.Solutions = result.Solutions .OrderBy(s => s.Id) .Skip((request.Paginator.Page - 1) * request.Paginator.ItemsPerPage) .Take(request.Paginator.ItemsPerPage) .ToList(); } else { foreach (var obj in response.Objects) { result.Solutions.Add((ISudokuSolution)obj); } result.Solutions = result.Solutions .OrderByDescending(s => s.Id) .Skip((request.Paginator.Page - 1) * request.Paginator.ItemsPerPage) .Take(request.Paginator.ItemsPerPage) .ToList(); } } else if (request.Paginator.SortBy == SortValue.DATECREATED) { if (!request.Paginator.OrderByDescending) { foreach (var obj in response.Objects) { result.Solutions.Add((ISudokuSolution)obj); } result.Solutions = result.Solutions .OrderBy(s => s.DateCreated) .Skip((request.Paginator.Page - 1) * request.Paginator.ItemsPerPage) .Take(request.Paginator.ItemsPerPage) .ToList(); } else { foreach (var obj in response.Objects) { result.Solutions.Add((ISudokuSolution)obj); } result.Solutions = result.Solutions .OrderByDescending(s => s.DateCreated) .Skip((request.Paginator.Page - 1) * request.Paginator.ItemsPerPage) .Take(request.Paginator.ItemsPerPage) .ToList(); } } else if (request.Paginator.SortBy == SortValue.DATEUPDATED) { if (!request.Paginator.OrderByDescending) { foreach (var obj in response.Objects) { result.Solutions.Add((ISudokuSolution)obj); } result.Solutions = result.Solutions .OrderBy(s => s.DateSolved) .Skip((request.Paginator.Page - 1) * request.Paginator.ItemsPerPage) .Take(request.Paginator.ItemsPerPage) .ToList(); } else { foreach (var obj in response.Objects) { result.Solutions.Add((ISudokuSolution)obj); } result.Solutions = result.Solutions .OrderByDescending(g => g.DateSolved) .Skip((request.Paginator.Page - 1) * request.Paginator.ItemsPerPage) .Take(request.Paginator.ItemsPerPage) .ToList(); } } else { result.Success = false; result.Message = ServicesMesages.SortValueNotImplementedMessage; return(result); } } else { result.Success = false; result.Message = ServicesMesages.PageNotFoundMessage; return(result); } } else { result.Solutions = response.Objects.ConvertAll(s => (ISudokuSolution)s); } if (fullRecord) { foreach (var solution in result.Solutions) { if (solution.Game != null) { solution.Game.SudokuMatrix.Difficulty.Matrices = null; } } } result.Success = response.Success; result.Message = SolutionsMessages.SolutionsFoundMessage; return(result); } else if (!response.Success && response.Exception != null) { result.Success = response.Success; result.Message = response.Exception.Message; return(result); } else { result.Success = false; result.Message = SolutionsMessages.SolutionsNotFoundMessage; return(result); } } catch (Exception exp) { result.Success = false; result.Message = exp.Message; return(result); } }
public BaseExecute(IBaseRequest request) { Request = request; }