Ejemplo n.º 1
0
        private async Task <ApiResponse <T> > Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            var codec = new CustomJsonCodec(configuration);

            req.JsonSerializer = codec;
            client.AddHandler(codec.ContentType, codec);

            client.Timeout = configuration.Timeout;

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            InterceptRequest(req);
            var response = await client.ExecuteTaskAsync <T>(req);

            InterceptResponse(req, response);

            var result = toApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Ejemplo n.º 2
0
        private async Task <ApiResponse <T> > ExecAsync <T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

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

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

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

            InterceptRequest(req);

            IRestResponse <T> response;

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

                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = await client.ExecuteAsync <T>(req, cancellationToken).ConfigureAwait(false);
            }

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

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Ejemplo n.º 3
0
        private async Task <ApiResponse <T> > Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler(existingDeserializer, "application/json", "text/json", "text/x-json", "text/javascript", "*+json");
            }
            else
            {
                var codec = new CustomJsonCodec(configuration);
                client.AddHandler(codec, "application/json", "text/json", "text/x-json", "text/javascript", "*+json");
            }

            client.AddHandler(new XmlDeserializer(), "application/xml", "text/xml", "*+xml", "*");

            client.Timeout = configuration.Timeout;

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

            InterceptRequest(req);
            var response = await client.ExecuteTaskAsync <T>(req);

            InterceptResponse(req, response);

            var result = toApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Ejemplo n.º 4
0
        private ApiResponse <T> Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

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

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

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

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.RetryPolicy != null)
            {
                var policy       = RetryConfiguration.RetryPolicy;
                var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = client.Execute <T>(req);
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Ejemplo n.º 5
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));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Provides all logic for constructing a new HttpRequestMessage.
        /// At this point, all information for querying the service is known. Here, it is simply
        /// mapped into the a HttpRequestMessage.
        /// </summary>
        /// <param name="method">The http verb.</param>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new HttpRequestMessage instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private HttpRequestMessage NewRequest(
            HttpMethod method,
            string path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path);

            builder.AddPathParameters(options.PathParameters);

            builder.AddQueryParameters(options.QueryParameters);

            HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri());

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

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    request.Headers.Add(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        // Todo make content headers actually content headers
                        request.Headers.TryAddWithoutValidation(headerParam.Key, value);
                    }
                }
            }

            List <Tuple <HttpContent, string, string> > contentList = new List <Tuple <HttpContent, string, string> >();

            string contentType = null;

            if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type"))
            {
                var contentTypes = options.HeaderParameters["Content-Type"];
                contentType = contentTypes.FirstOrDefault();
            }

            if (contentType == "multipart/form-data")
            {
                request.Content = PrepareMultipartFormDataContent(options);
            }
            else if (contentType == "application/x-www-form-urlencoded")
            {
                request.Content = new FormUrlEncodedContent(options.FormParameters);
            }
            else
            {
                if (options.Data != null)
                {
                    if (options.Data is FileParameter fp)
                    {
                        contentType = contentType ?? "application/octet-stream";

                        var streamContent = new StreamContent(fp.Content);
                        streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                        request.Content = streamContent;
                    }
                    else
                    {
                        var serializer = new CustomJsonCodec(SerializerSettings, configuration);
                        request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(),
                                                            "application/json");
                    }
                }
            }



            // TODO provide an alternative that allows cookies per request instead of per API client
            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                request.Properties["CookieContainer"] = options.Cookies;
            }

            return(request);
        }
Ejemplo n.º 7
0
        private ApiResponse <T> Exec <T>(RestRequest req, IReadableConfiguration configuration)
        {
            RestClient client = new RestClient(_baseUrl);

            client.ClearHandlers();
            var existingDeserializer = req.JsonSerializer as IDeserializer;

            if (existingDeserializer != null)
            {
                client.AddHandler("application/json", () => existingDeserializer);
                client.AddHandler("text/json", () => existingDeserializer);
                client.AddHandler("text/x-json", () => existingDeserializer);
                client.AddHandler("text/javascript", () => existingDeserializer);
                client.AddHandler("*+json", () => existingDeserializer);
            }
            else
            {
                var customDeserializer = new CustomJsonCodec(configuration);
                client.AddHandler("application/json", () => customDeserializer);
                client.AddHandler("text/json", () => customDeserializer);
                client.AddHandler("text/x-json", () => customDeserializer);
                client.AddHandler("text/javascript", () => customDeserializer);
                client.AddHandler("*+json", () => customDeserializer);
            }

            var xmlDeserializer = new XmlDeserializer();

            client.AddHandler("application/xml", () => xmlDeserializer);
            client.AddHandler("text/xml", () => xmlDeserializer);
            client.AddHandler("*+xml", () => xmlDeserializer);
            client.AddHandler("*", () => xmlDeserializer);

            client.Timeout = configuration.Timeout;

            if (configuration.UserAgent != null)
            {
                client.UserAgent = configuration.UserAgent;
            }

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

            InterceptRequest(req);

            IRestResponse <T> response;

            if (RetryConfiguration.RetryPolicy != null)
            {
                var policy       = RetryConfiguration.RetryPolicy;
                var policyResult = policy.ExecuteAndCapture(() => client.Execute(req));
                response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize <T>(policyResult.Result) : new RestResponse <T>
                {
                    Request        = req,
                    ErrorException = policyResult.FinalException
                };
            }
            else
            {
                response = client.Execute <T>(req);
            }

            // 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 });
                response.Data = instance;
            }

            InterceptResponse(req, response);

            var result = ToApiResponse(response);

            if (response.ErrorMessage != null)
            {
                result.ErrorText = response.ErrorMessage;
            }

            if (response.Cookies != null && response.Cookies.Count > 0)
            {
                if (result.Cookies == null)
                {
                    result.Cookies = new List <Cookie>();
                }
                foreach (var restResponseCookie in response.Cookies)
                {
                    var cookie = new Cookie(
                        restResponseCookie.Name,
                        restResponseCookie.Value,
                        restResponseCookie.Path,
                        restResponseCookie.Domain
                        )
                    {
                        Comment    = restResponseCookie.Comment,
                        CommentUri = restResponseCookie.CommentUri,
                        Discard    = restResponseCookie.Discard,
                        Expired    = restResponseCookie.Expired,
                        Expires    = restResponseCookie.Expires,
                        HttpOnly   = restResponseCookie.HttpOnly,
                        Port       = restResponseCookie.Port,
                        Secure     = restResponseCookie.Secure,
                        Version    = restResponseCookie.Version
                    };

                    result.Cookies.Add(cookie);
                }
            }
            return(result);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Provides all logic for constructing a new HttpRequestMessage.
        /// At this point, all information for querying the service is known. Here, it is simply
        /// mapped into the a HttpRequestMessage.
        /// </summary>
        /// <param name="method">The http verb.</param>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new HttpRequestMessage instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private HttpRequestMessage NewRequest(
            HttpMethod method,
            String path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path);

            builder.AddPathParameters(options.PathParameters);

            // In case of POST or PUT pass query parameters in request body
            if (method != HttpMethod.Post && method != HttpMethod.Put)
            {
                builder.AddQueryParameters(options.QueryParameters);
            }

            HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri());

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    request.Headers.Add(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        // Todo make content headers actually content headers
                        request.Headers.TryAddWithoutValidation(headerParam.Key, value);
                    }
                }
            }

            List <Tuple <HttpContent, string, string> > contentList = new List <Tuple <HttpContent, string, string> >();

            if (options.FormParameters != null && options.FormParameters.Count > 0)
            {
                contentList.Add(new Tuple <HttpContent, string, string>(new FormUrlEncodedContent(options.FormParameters), null, null));
            }

            if (options.Data != null)
            {
                var serializer = new CustomJsonCodec(SerializerSettings, configuration);
                contentList.Add(
                    new Tuple <HttpContent, string, string>(new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(), "application/json"), null, null));
            }

            if (options.FileParameters != null && options.FileParameters.Count > 0)
            {
                foreach (var fileParam in options.FileParameters)
                {
                    var bytes      = ClientUtils.ReadAsBytes(fileParam.Value);
                    var fileStream = fileParam.Value as FileStream;
                    contentList.Add(new Tuple <HttpContent, string, string>(new ByteArrayContent(bytes), fileParam.Key,
                                                                            fileStream?.Name ?? "no_file_name_provided"));
                }
            }

            if (contentList.Count > 1)
            {
                string boundary         = "---------" + Guid.NewGuid().ToString().ToUpperInvariant();
                var    multipartContent = new MultipartFormDataContent(boundary);
                foreach (var content in contentList)
                {
                    if (content.Item2 != null)
                    {
                        multipartContent.Add(content.Item1, content.Item2, content.Item3);
                    }
                    else
                    {
                        multipartContent.Add(content.Item1);
                    }
                }

                request.Content = multipartContent;
            }
            else
            {
                request.Content = contentList.FirstOrDefault()?.Item1;
            }

            // TODO provide an alternative that allows cookies per request instead of per API client
            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                request.Properties["CookieContainer"] = options.Cookies;
            }

            return(request);
        }