2024-05-05 18:00:10 +04:00
|
|
|
|
using Azure.Core;
|
|
|
|
|
using DinerContracts.ViewModels;
|
2024-05-01 22:39:51 +04:00
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
using System.Net.Http.Headers;
|
|
|
|
|
using System.Net.WebSockets;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
|
|
namespace DinerClientApp {
|
|
|
|
|
public class APIClient {
|
|
|
|
|
private static readonly HttpClient _client = new();
|
|
|
|
|
|
|
|
|
|
public static ClientViewModel? Client { get; set; } = null;
|
|
|
|
|
|
2024-05-05 18:00:10 +04:00
|
|
|
|
public static void Connect(IConfiguration configuration) {
|
2024-05-01 22:39:51 +04:00
|
|
|
|
_client.BaseAddress = new Uri(configuration["IPAddress"]);
|
|
|
|
|
_client.DefaultRequestHeaders.Accept.Clear();
|
|
|
|
|
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-05 18:00:10 +04:00
|
|
|
|
public static T? GetRequest<T>(string requestUrl) {
|
|
|
|
|
var response = _client.GetAsync(requestUrl);
|
|
|
|
|
var result = response.Result.Content.ReadAsStringAsync().Result;
|
|
|
|
|
if (response.Result.IsSuccessStatusCode) {
|
2024-05-01 22:39:51 +04:00
|
|
|
|
return JsonConvert.DeserializeObject<T>(result);
|
|
|
|
|
}
|
|
|
|
|
else {
|
|
|
|
|
throw new Exception(result);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-05 18:00:10 +04:00
|
|
|
|
public static void PostRequset<T>(string requestUrl, T model) {
|
2024-05-01 22:39:51 +04:00
|
|
|
|
var json = JsonConvert.SerializeObject(model);
|
|
|
|
|
var data = new StringContent(json, Encoding.UTF8, "application/json");
|
|
|
|
|
|
2024-05-05 18:00:10 +04:00
|
|
|
|
var response = _client.PostAsync(requestUrl, data);
|
2024-05-01 22:39:51 +04:00
|
|
|
|
|
|
|
|
|
var result = response.Result.Content.ReadAsStringAsync().Result;
|
|
|
|
|
if (!response.Result.IsSuccessStatusCode) {
|
|
|
|
|
throw new Exception(result);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|