Esempio n. 1
0
        /// <summary>
        /// Send a POST or PUT operation expecting a result from a JSON type.
        /// </summary>
        /// <param name="operation"></param>Http
        /// <param name="serviceRoute">specified route prefix to connect to the service</param>
        /// <param name="body">all the information enclosed in the message body in the JSON format</param>
        /// <param name="headers">pass additional information with the request or the response</param>
        /// <returns></returns>
        private JToken Send(string operation, string serviceRoute, [Optional] JToken body, Dictionary <string, string> headers)
        {
            serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");

            HttpClient httpClient = new HttpClient();

            try
            {
                if (body == null)
                {
                    body = new JObject();
                }

                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        httpClient.DefaultRequestHeaders.Add(item.Key, item.Value);
                    }
                }

                /// Sends a authorizarion token, if it exists
                if (!string.IsNullOrEmpty(_token))
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
                }

                WorkBenchServiceHttp httpMethod = WorkBenchServiceHttp.POST;
                if (operation == "PUT")
                {
                    httpMethod = WorkBenchServiceHttp.PUT;
                }

                var httpResponse = base.ResilientRequest(this.MakeUri(serviceRoute), httpClient, httpMethod, body.ConvertToByteArrayContent()).Result;

                JToken result = JToken.Parse(httpResponse.Content.ReadAsStringAsync().Result);

                return(HandleResult(result));
            }
            ///Catchs the Exception calling the API and throw
            catch (Exception ex)
            {
                string exBody = body != null?body.ToString() : "null";

                StringBuilder sb = new StringBuilder();
                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        sb.AppendLine($"{item.Key} = {item.Value}");
                    }
                }
                else
                {
                    sb.Append("header = vazio");
                }
                throw new LightException($"Error on API call Rest. OP: {operation} || SR: {MakeUri(serviceRoute)} || BD: {exBody} || HD: {sb.ToString()} || EX: {ex.Message} || ST:{ex.StackTrace}", ex);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Resilient request using Polly
        /// </summary>
        /// <param name="URL"></param>
        /// <param name="httpClient"></param>
        /// <param name="http"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        internal async Task <HttpResponseMessage> ResilientRequest(string URL, HttpClient httpClient, WorkBenchServiceHttp http, ByteArrayContent data = null)
        {
            if (_stub)
            {
                var config = new MockData().GetMockData <StubAPIConfiguration>("stubAPIData");
                if (config != null)
                {
                    HostStubAPIConfiguration host = config.Hosts.Where(x => x.Name == _apiname).FirstOrDefault();
                    if (host != null)
                    {
                        MethodStubAPIConfiguration method = host.Methods.Where(x => x.WorkBenchServiceHttp == http &&
                                                                               Regex.Matches(URL, x.Route, RegexOptions.IgnoreCase).FirstOrDefault() != null
                                                                               ).FirstOrDefault();

                        string jsonString = (new { PayLoad = method.Response, critics = new List <Critic>() }).ToStringCamelCase();
                        return(await Task.FromResult(new HttpResponseMessage()
                        {
                            StatusCode = HttpStatusCode.OK,
                            Content = new StringContent(jsonString, System.Text.Encoding.UTF8),
                        }));
                    }
                    else
                    {
                        throw new LightException($"Workbench cannot made the request for: {URL} by STUB, there isn't host for request.");
                    }
                }
                else
                {
                    throw new LightException($"Workbench cannot made the request for: {URL} by STUB, check the configuration file.");
                }
            }
            else
            {
                if (this.Polly != null)
                {
                    return(await this.Polly.ResilientRequest(URL, httpClient, http, LightConfigurator.Config <ApiConfiguration>(this._apiname).Polly, data));
                }
                else
                {
                    switch (http)
                    {
                    case WorkBenchServiceHttp.GET:
                        return(await httpClient.GetAsync(URL));

                    case WorkBenchServiceHttp.POST:
                        return(await httpClient.PostAsync(URL, data));

                    case WorkBenchServiceHttp.PUT:
                        return(await httpClient.PutAsync(URL, data));

                    case WorkBenchServiceHttp.DELETE:
                        return(await httpClient.DeleteAsync(URL));

                    default:
                        throw new LightException($"Workbench cannot made the request for: {URL}");
                    }
                }
            }
        }
Esempio n. 3
0
        public override async Task <HttpResponseMessage> ResilientRequest(string url, HttpClient httpClient, WorkBenchServiceHttp http, dynamic pollyconfiguration, object data = null)
        {
            PollyConfiguration pollyConfig = (PollyConfiguration)pollyconfiguration;
            AsyncRetryPolicy <HttpResponseMessage> retryPolicy = null;

            retryPolicy = pollyConfig.IsBackOff == true?Policy.HandleResult <HttpResponseMessage>(r => r.StatusCode.Equals(HttpStatusCode.InternalServerError))
                          .Or <WebException>().Or <HttpRequestException>()
                          .WaitAndRetryAsync(pollyConfig.Retry, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (result, timeSpan, retryCount, context) =>
            {
                CallbackError <HttpResponseMessage>(result, timeSpan, retryCount);
            }) :

                              Policy.HandleResult <HttpResponseMessage>(r => r.StatusCode.Equals(HttpStatusCode.InternalServerError)).Or <WebException>().Or <HttpRequestException>()
                              .WaitAndRetryAsync(pollyConfig.Retry, retryAttempt => TimeSpan.FromSeconds(pollyConfig.Wait), (result, timeSpan, retryCount, context) =>
            {
                CallbackError <HttpResponseMessage>(result, timeSpan, retryCount);
            });

            return(await retryPolicy.ExecuteAsync(() =>
            {
                switch (http)
                {
                case WorkBenchServiceHttp.GET:
                    return httpClient.GetAsync(url);

                case WorkBenchServiceHttp.POST:
                    return httpClient.PostAsync(url, (HttpContent)data);

                case WorkBenchServiceHttp.PUT:
                    return httpClient.PutAsync(url, (HttpContent)data);

                case WorkBenchServiceHttp.DELETE:
                    return httpClient.DeleteAsync(url);

                default:
                    return null;
                }
            }));
        }
Esempio n. 4
0
 public abstract Task <HttpResponseMessage> ResilientRequest(string url, HttpClient httpClient, WorkBenchServiceHttp http, dynamic pollyconfiguration, object data = null);