Esempio n. 1
0
        private async Task <ApiResponse <T> > ExecAsync <T>(HttpRequestMessage req,
                                                            IReadableConfiguration configuration,
                                                            System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var deserializer = new CustomJsonCodec(SerializerSettings, configuration);

            var finalToken = cancellationToken;

            if (configuration.Timeout > 0)
            {
                var tokenSource = new CancellationTokenSource(configuration.Timeout);
                finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token;
            }

            if (configuration.Proxy != null)
            {
                if (_httpClientHandler == null)
                {
                    throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
                }
                _httpClientHandler.Proxy = configuration.Proxy;
            }

            if (configuration.ClientCertificates != null)
            {
                if (_httpClientHandler == null)
                {
                    throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
                }
                _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates);
            }

            var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List <Cookie> : null;

            if (cookieContainer != null)
            {
                if (_httpClientHandler == null)
                {
                    throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor.");
                }
                foreach (var cookie in cookieContainer)
                {
                    _httpClientHandler.CookieContainer.Add(cookie);
                }
            }

            InterceptRequest(req);

            HttpResponseMessage response;

            if (RetryConfiguration.AsyncRetryPolicy != null)
            {
                var policy       = RetryConfiguration.AsyncRetryPolicy;
                var policyResult = await policy
                                   .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken))
                                   .ConfigureAwait(false);

                response = (policyResult.Outcome == OutcomeType.Successful) ?
                           policyResult.Result : new HttpResponseMessage()
                {
                    ReasonPhrase   = policyResult.FinalException.ToString(),
                    RequestMessage = req
                };
            }
            else
            {
                response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false);
            }

            if (!response.IsSuccessStatusCode)
            {
                return(await ToApiResponse <T>(response, default(T), req.RequestUri));
            }

            object responseData = await deserializer.Deserialize <T>(response);

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                responseData = (T)typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content });
            }
            else if (typeof(T).Name == "Stream") // for binary response
            {
                responseData = (T)(object)await response.Content.ReadAsStreamAsync();
            }

            InterceptResponse(req, response);

            return(await ToApiResponse <T>(response, responseData, req.RequestUri));
        }
Esempio n. 2
0
        private async Task <ApiResponse <T> > ExecAsync <T>(HttpRequestMessage req,
                                                            IReadableConfiguration configuration,
                                                            System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            var handler      = new HttpClientHandler();
            var client       = new HttpClient();
            var deserializer = new CustomJsonCodec(SerializerSettings, configuration);

            var finalToken = cancellationToken;

            if (configuration.Timeout > 0)
            {
                var tokenSource = new CancellationTokenSource(configuration.Timeout);
                finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token;
            }

            if (configuration.Proxy != null)
            {
                handler.Proxy = configuration.Proxy;
            }

            if (configuration.UserAgent != null)
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", configuration.UserAgent);
            }

            if (configuration.ClientCertificates != null)
            {
                handler.ClientCertificates.AddRange(configuration.ClientCertificates);
            }

            var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List <Cookie> : null;

            if (cookieContainer != null)
            {
                foreach (var cookie in cookieContainer)
                {
                    handler.CookieContainer.Add(cookie);
                }
            }

            InterceptRequest(req, handler);

            HttpResponseMessage response;

            if (RetryConfiguration.AsyncRetryPolicy != null)
            {
                var policy       = RetryConfiguration.AsyncRetryPolicy;
                var policyResult = await policy
                                   .ExecuteAndCaptureAsync(() => client.SendAsync(req, cancellationToken))
                                   .ConfigureAwait(false);

                response = (policyResult.Outcome == OutcomeType.Successful) ?
                           policyResult.Result : new HttpResponseMessage()
                {
                    ReasonPhrase   = policyResult.FinalException.ToString(),
                    RequestMessage = req
                };
            }
            else
            {
                response = await client.SendAsync(req, cancellationToken).ConfigureAwait(false);
            }

            object responseData = deserializer.Deserialize <T>(response);

            // if the response type is oneOf/anyOf, call FromJSON to deserialize the data
            if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T)))
            {
                T          instance = (T)Activator.CreateInstance(typeof(T));
                MethodInfo method   = typeof(T).GetMethod("FromJson");
                method.Invoke(instance, new object[] { response.Content });
                responseData = instance;
            }
            else if (typeof(T).Name == "Stream") // for binary response
            {
                responseData = (T)(object)await response.Content.ReadAsStreamAsync();
            }

            InterceptResponse(req, response);

            var result = ToApiResponse <T>(response, responseData, handler, req.RequestUri);

            return(result);
        }