Beispiel #1
0
        /// <summary>
        /// Send a POST or PUT operation expecting a result from a JSON type.
        /// </summary>
        protected override async Task <T> SendAsync <T>(string operation, string serviceRoute, FormUrlEncodedContent body, Dictionary <string, string> headers)
        {
            serviceRoute = serviceRoute.Replace(Environment.NewLine, string.Empty).Replace("\"", "'");

            try
            {
                ///Send the authentication token if exisists
                if (!String.IsNullOrEmpty(_token))
                {
                    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);
                }


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

                HttpResponseMessage response;

                if (operation == "POST")
                {
                    response = await base.ResilientRequest(MakeUri(serviceRoute), _httpClient, WorkBenchServiceHttp.POST, body.ConvertToByteArrayContent());
                }
                else
                {
                    response = await base.ResilientRequest(MakeUri(serviceRoute), _httpClient, WorkBenchServiceHttp.PUT, body.ConvertToByteArrayContent());
                }

                if (typeof(T).Equals(typeof(HttpResponseMessage)))
                {
                    return((T)Convert.ChangeType(response, typeof(T)));
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    JToken result = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                    return(HandleResult <T>(result));
                }
            }
            ///Catchs the Exception calling the API
            catch (Exception ex)
            {
                throw new LightException($"Error on API call Rest. OP: {operation} || SR: {MakeUri(serviceRoute)} || EX: {ex.Message} || ST:{ex.StackTrace}", ex);
            }
            ///return JToken
            return(default(T));
        }