Files
EmptyMauiApp/MauiApp/Core/RestClient/ApiRestClient.cs
2023-10-18 19:02:51 +02:00

81 lines
2.4 KiB
C#

using System.Net;
using System.Text;
using System.Text.Json;
using MauiApp.Core.Converter;
using MauiApp.Core.RestClient.Contracts;
namespace MauiApp.Core.RestClient;
public abstract class ApiRestClient : IApiRestClient
{
public string BaseUrl { get; init; }
public static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
Converters =
{
new DateTimeConverter(),
new NullableDateTimeConverter(),
}
};
public async Task<T> Get<T>(string url, IDictionary<string, object> queryParams = null, HttpClient httpClient = null)
{
queryParams ??= new Dictionary<string, object>();
var queryParamString = string.Join("&",
queryParams.Select(kvp =>
$"{kvp.Key}={kvp.Value}"));
httpClient ??= new HttpClient();
httpClient.BaseAddress = new Uri(BaseUrl);
T response = default;
try
{
var content = await httpClient.GetStreamAsync($"{url}?{queryParamString}");
response = await JsonSerializer.DeserializeAsync<T>(content, JsonSerializerOptions);
}
catch (Exception ex)
{
throw new Exception("Errore interno " + ex + response);
}
finally
{
httpClient.Dispose();
}
return response;
}
public async Task<T> Post<T>(string url, object body, IDictionary<string, object> queryParams = null, HttpClient httpClient = null)
{
queryParams ??= new Dictionary<string, object>();
var queryParamString = string.Join("&",
queryParams.Select(kvp =>
$"{kvp.Key}={kvp.Value}"));
httpClient ??= new HttpClient();
httpClient.BaseAddress = new Uri(BaseUrl);
var jsonBody = JsonSerializer.Serialize(body, JsonSerializerOptions);
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync($"{url}?{queryParamString}", content);
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(response.ReasonPhrase);
var jsonResponse = await response.Content.ReadAsStreamAsync();
var result = await JsonSerializer.DeserializeAsync<T>(jsonResponse, JsonSerializerOptions);
httpClient.Dispose();
return result;
}
}