61 lines
1.8 KiB
C#

using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace AutoWorkshopShopApp
{
public class ApiClient
{
private static readonly HttpClient _client = new();
public static string? Password { get; set; }
public static bool IsAuthenticated { get; private set; } = false;
public static bool TryAuthenticate(string Password)
{
if (Password == ApiClient.Password)
{
IsAuthenticated = true;
}
return IsAuthenticated;
}
public static void Connect(IConfiguration Configuration)
{
Password = Configuration["Password"];
_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);
}
}
}
}