52 lines
2.1 KiB
C#
52 lines
2.1 KiB
C#
|
using Newtonsoft.Json;
|
|||
|
using System;
|
|||
|
using System.Net.Http;
|
|||
|
using System.Text;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace Netmash.Extensions.Http
|
|||
|
{
|
|||
|
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;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|