netmash/Netmash.Extensions.Http/HttpClientExtensions.cs

52 lines
2.1 KiB
C#
Raw Normal View History

2020-12-21 00:44:37 +02:00
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
2023-01-12 01:01:36 +02:00
namespace Netmash.Extensions.Http
2020-12-21 00:44:37 +02:00
{
public static class HttpClientExtensions
{
private const string _contentType = "application/json";
public static async Task<T> ExecuteGetRequest<T>(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<T>(await response.Content.ReadAsStringAsync());
return result;
}
}
public static async Task<R> ExecutePostRequest<R>(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<R>(await response.Content.ReadAsStringAsync());
return result;
}
}
public static async Task<R> ExecutePostRequest<R, B>(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<R>(await response.Content.ReadAsStringAsync());
return result;
}
}
}
}