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(); }
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(); }