Exemple #1
0
        private async Task <HttpResponseMessage> SendAsJsonAsync(HttpMethod method, string endpoint, IEnumerable <KeyValuePair <string, object> > parameters = null)
        {
            PrepareForAuthenticate(method, _baseUrl + endpoint, ref parameters);
            var dict = new Dictionary <string, object>();

            if (parameters != null)
            {
                foreach (var kvp in parameters)
                {
                    if (dict.ContainsKey(kvp.Key))
                    {
                        throw new InvalidOperationException();
                    }
                    dict.Add(kvp.Key, kvp.Value);
                }
            }
            var body     = JsonConvert.SerializeObject(dict);
            var content  = new StringContent(body, Encoding.UTF8, "application/json");
            var response = await _httpClient.SendAsync(new HttpRequestMessage(method, _baseUrl + endpoint) { Content = content }).Stay();

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }
            throw await DisboardException.Create(response, _baseUrl + endpoint);
        }
Exemple #2
0
        /// <summary>
        ///     Send a DELETE request to endpoint with parameters.
        /// </summary>
        /// <param name="endpoint">Endpoint of API without base url.</param>
        /// <param name="parameters">Parameters</param>
        /// <returns>API response</returns>
        public async Task <string> DeleteAsync(string endpoint, IEnumerable <KeyValuePair <string, object> > parameters = null)
        {
            if (parameters != null && parameters.Any())
            {
                endpoint += $"?{string.Join("&", AsUrlParameter(parameters))}";
            }

            var response = await _httpClient.DeleteAsync(_baseUrl + endpoint).Stay();

            if (response.IsSuccessStatusCode)
            {
                return(await response.Content.ReadAsStringAsync().Stay());
            }
            throw await DisboardException.Create(response, _baseUrl + endpoint).Stay();
        }
Exemple #3
0
        private async Task <HttpResponseMessage> GetAsyncInternal(string endpoint, IEnumerable <KeyValuePair <string, object> > parameters = null)
        {
            if (parameters != null && parameters.Any())
            {
                endpoint += $"?{string.Join("&", AsUrlParameter(parameters))}";
            }

            var response = await _httpClient.GetAsync(_baseUrl + endpoint).Stay();

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }
            throw await DisboardException.Create(response, _baseUrl + endpoint).Stay();
        }
Exemple #4
0
        private async Task <HttpResponseMessage> SendAsJsonAsync(HttpMethod method, string endpoint, IEnumerable <KeyValuePair <string, object> > parameters = null)
        {
            if (parameters != null && parameters.Any(w => BinaryParameters.Contains(w.Key)))
            {
                return(await SendAsFormDataAsync(method, endpoint, parameters).Stay());
            }

            var body     = JsonConvert.SerializeObject(parameters != null ? parameters.ToDictionary(w => w.Key, w => w.Value) : new Dictionary <string, object>());
            var content  = new StringContent(body, Encoding.UTF8, "application/json");
            var response = await _httpClient.SendAsync(new HttpRequestMessage(method, _baseUrl + endpoint) { Content = content }).Stay();

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }
            throw await DisboardException.Create(response, _baseUrl + endpoint).Stay();
        }
Exemple #5
0
        private async Task <HttpResponseMessage> SendAsFormDataAsync(HttpMethod method, string endpoint, IEnumerable <KeyValuePair <string, object> > parameters = null)
        {
            HttpResponseMessage response;

            if (parameters == null)
            {
                response = await _httpClient.SendAsync(new HttpRequestMessage(method, _baseUrl + endpoint)).Stay();
            }
            else
            {
                HttpContent content;
                if (parameters.Any(w => BinaryParameters.Contains(w.Key)))
                {
                    content = new MultipartFormDataContent();

                    foreach (var parameter in parameters)
                    {
                        HttpContent formDataContent;
                        if (BinaryParameters.Contains(parameter.Key))
                        {
                            using (var stream = new FileStream(parameter.Value.ToString(), FileMode.Open))
                                formDataContent = new ByteArrayContent(ReadAsByteArray(stream));
                            formDataContent.Headers.Add("Content-Disposition", $"form-data; name=\"{parameter.Key}\"; filename=\"{Path.GetFileName(parameter.Value.ToString())}\"");
                        }
                        else
                        {
                            formDataContent = new StringContent(NormalizeBoolean(parameter.Value));
                        }
                        ((MultipartFormDataContent)content).Add(formDataContent, parameter.Key);
                    }
                }
                else
                {
                    var kvpCollection = parameters.Select(w => new KeyValuePair <string, string>(w.Key, NormalizeBoolean(w.Value)));
                    content = new FormUrlEncodedContent(kvpCollection);
                }
                response = await _httpClient.SendAsync(new HttpRequestMessage(method, _baseUrl + endpoint) { Content = content }).Stay();
            }

            if (response.IsSuccessStatusCode)
            {
                return(response);
            }
            throw await DisboardException.Create(response, _baseUrl + endpoint).Stay();
        }
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var asmPath = $"{_assembly.FullName.Split(",")[0]}.data.{await CreateRequestHash(request)}.json";

            // If dump file exists, use dumped HTTP response.
            var stream = _assembly.GetManifestResourceStream(asmPath);

            if (stream != null)
            {
                using (var sr = new StreamReader(stream))
                {
                    var content = JsonConvert.DeserializeObject <HttpResponse>(await sr.ReadToEndAsync());
                    if (200 <= (int)content.StatusCode && (int)content.StatusCode <= 299)
                    {
                        return new HttpResponseMessage(content.StatusCode)
                               {
                                   Content = new StringContent(content.Body)
                               }
                    }
                    ;
                    throw DisboardException.Create(content.StatusCode, content.Body, request.RequestUri.ToString());
                }
            }

            var path = AsProjectDataPath($"{await CreateRequestHash(request)}.json");

#if DEBUG
            var response = await base.SendAsync(request, cancellationToken);

            using (var sw = new StreamWriter(path))
                sw.WriteLine(JsonConvert.SerializeObject(new HttpResponse {
                    StatusCode = response.StatusCode, Body = await response.Content.ReadAsStringAsync()
                }));
            await UpdateMapper(request);

            return(response);
#else
            throw new InvalidOperationException();
#endif
        }