public HttpClient GetHttpClient(HttpClientTypes httpClientType)
 {
     if (Enum.IsDefined(typeof(HttpClientTypes), httpClientType))
     {
         return(httpClientFactory.CreateClient(httpClientType.ToString()));
     }
     else
     {
         throw loggedExceptionFetcher.GetLoggedException($"Unsupported httpclient '{httpClientType}'", "Failed to return http client");
     }
 }
Пример #2
0
        public async Task <TResult> CallEndpoint <TResult> (
            HttpClientTypes httpClientType,
            string relativePath,
            HttpMethod method,
            object payload,
            Action <HttpRequestMessage> onBeforeRequest)
        {
            var endpointUri = new Uri($"{environmentSpecificValues.BaseUrl}{relativePath}");

            // Don't wrap httpClient in a 'using' block.
            // See: https://josef.codes/you-are-probably-still-using-httpclient-wrong-and-it-is-destabilizing-your-software/
            var httpClient = customHttpClientProvider.GetHttpClient(httpClientType);

            try
            {
                using (var request = new HttpRequestMessage(method, endpointUri))
                {
                    SetPayloadIfAvailable(request, payload);
                    FireCallbackIfAvailable(request, onBeforeRequest);
                    using (var response = await httpClient.SendAsync(request))
                    {
                        var responseData = await response.Content.ReadAsStringAsync();

                        ReportFailureIfAny(response, relativePath, responseData);
                        return(JsonConvert.DeserializeObject <TResult> (responseData));
                    }
                }
            }
            catch (Exception e)
            {
                logWriter.LogException(e, "Error making call to M-Pesa");
                throw;
            }
            finally
            {
                onBeforeRequest = null;
            }
        }