50 lines
1.6 KiB
C#
50 lines
1.6 KiB
C#
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;
|
|
|
|
public static void Connect(IConfiguration Configuration)
|
|
{
|
|
_client.BaseAddress = new Uri(Configuration["IPAddress"]);
|
|
_client.DefaultRequestHeaders.Accept.Clear();
|
|
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
}
|
|
|
|
public static T? GetRequest<T>(string RequestUrl)
|
|
{
|
|
var Response = _client.GetAsync(RequestUrl);
|
|
var Result = Response.Result.Content.ReadAsStringAsync().Result;
|
|
|
|
if (Response.Result.IsSuccessStatusCode)
|
|
{
|
|
return JsonConvert.DeserializeObject<T>(Result);
|
|
}
|
|
else
|
|
{
|
|
throw new Exception(Result);
|
|
}
|
|
}
|
|
|
|
public static void PostRequest<T>(string RequestUrl, T Model)
|
|
{
|
|
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;
|
|
|
|
if (!Response.Result.IsSuccessStatusCode)
|
|
{
|
|
throw new Exception(Result);
|
|
}
|
|
}
|
|
}
|
|
}
|