PIbd-22_Shabunov_O.A._AutoW.../AutoWorkshopClientApp/ApiClient.cs

50 lines
1.6 KiB
C#
Raw Normal View History

2024-04-11 14:21:59 +04:00
using AutoWorkshopContracts.ViewModels;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace AutoWorkshopClientApp
{
public static class ApiClient
{
private static readonly HttpClient _client = new();
public static ClientViewModel? Client { get; set; } = null;
2024-04-13 00:16:40 +04:00
public static void Connect(IConfiguration Configuration)
2024-04-11 14:21:59 +04:00
{
2024-04-13 00:16:40 +04:00
_client.BaseAddress = new Uri(Configuration["IPAddress"]);
2024-04-11 14:21:59 +04:00
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
2024-04-13 00:16:40 +04:00
public static T? GetRequest<T>(string RequestUrl)
2024-04-11 14:21:59 +04:00
{
2024-04-13 00:16:40 +04:00
var Response = _client.GetAsync(RequestUrl);
var Result = Response.Result.Content.ReadAsStringAsync().Result;
2024-04-11 14:21:59 +04:00
2024-04-13 00:16:40 +04:00
if (Response.Result.IsSuccessStatusCode)
2024-04-11 14:21:59 +04:00
{
2024-04-13 00:16:40 +04:00
return JsonConvert.DeserializeObject<T>(Result);
2024-04-11 14:21:59 +04:00
}
else
{
2024-04-13 00:16:40 +04:00
throw new Exception(Result);
2024-04-11 14:21:59 +04:00
}
}
2024-04-13 00:16:40 +04:00
public static void PostRequest<T>(string RequestUrl, T Model)
2024-04-11 14:21:59 +04:00
{
2024-04-13 00:16:40 +04:00
var Json = JsonConvert.SerializeObject(Model);
var Data = new StringContent(Json, Encoding.UTF8, "application/json");
var Response = _client.PostAsync(RequestUrl, Data);
var Result = Response.Result.Content.ReadAsStringAsync().Result;
2024-04-11 14:21:59 +04:00
2024-04-13 00:16:40 +04:00
if (!Response.Result.IsSuccessStatusCode)
2024-04-11 14:21:59 +04:00
{
2024-04-13 00:16:40 +04:00
throw new Exception(Result);
2024-04-11 14:21:59 +04:00
}
}
}
}