using Newtonsoft.Json; using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace NDB.Extensions.Http { public static class HttpClientExtensions { private const string _contentType = "application/json"; public static async Task ExecuteGetRequest(this HttpClient httpClient, string route) where T : class { using (var response = await httpClient.GetAsync(route)) { if (!response.IsSuccessStatusCode) throw new Exception($"Error: StatusCode: {response.StatusCode}; Reason: {response.ReasonPhrase}"); var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return result; } } public static async Task ExecutePostRequest(this HttpClient httpClient, string route) where R : class { HttpContent content = new StringContent(JsonConvert.SerializeObject(string.Empty), Encoding.UTF8, _contentType); using (var response = await httpClient.PostAsync(route, content)) { if (!response.IsSuccessStatusCode) throw new Exception($"Error: StatusCode: {response.StatusCode}; Reason: {response.ReasonPhrase}"); var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return result; } } public static async Task ExecutePostRequest(this HttpClient httpClient, string route, B body) where R : class where B : class { HttpContent content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, _contentType); using (var response = await httpClient.PostAsync(route, content)) { if (!response.IsSuccessStatusCode) throw new Exception($"Error: StatusCode: {response.StatusCode}; Reason: {response.ReasonPhrase}"); var result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); return result; } } } }