52 lines
1.7 KiB
C#
52 lines
1.7 KiB
C#
using Microsoft.AspNetCore.Components.Authorization;
|
|
|
|
namespace OrdersManagement.Services;
|
|
|
|
public class ServiceBase<T> where T : class
|
|
{
|
|
private readonly AuthenticationStateProvider _authenticationStateProvider;
|
|
private readonly HttpClient _httpClient;
|
|
|
|
protected ServiceBase(IHttpClientFactory httpClientFactory, AuthenticationStateProvider authenticationStateProvider)
|
|
{
|
|
_authenticationStateProvider = authenticationStateProvider;
|
|
_httpClient = httpClientFactory.CreateClient("FaKrosnoApi");
|
|
|
|
_ = Configure();
|
|
}
|
|
|
|
protected async Task<IEnumerable<T>?> GetListAsync(string request)
|
|
{
|
|
var response = await _httpClient.GetAsync(request);
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<IEnumerable<T>>();
|
|
}
|
|
|
|
protected async Task<T?> GetByIdAsync(string request)
|
|
{
|
|
var response = await _httpClient.GetAsync(request);
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<T>();
|
|
}
|
|
|
|
protected async Task<HttpResponseMessage> PostAsync(string request)
|
|
{
|
|
var response = await _httpClient.PostAsync(request, null);
|
|
response.EnsureSuccessStatusCode();
|
|
return response;
|
|
}
|
|
|
|
private async Task Configure()
|
|
{
|
|
var token = await GetToken();
|
|
|
|
_httpClient.DefaultRequestHeaders.Authorization =
|
|
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
|
}
|
|
|
|
private async Task<string?> GetToken()
|
|
{
|
|
await ((CustomAuthenticationStateProvider)_authenticationStateProvider).InitializeAsync();
|
|
return ((CustomAuthenticationStateProvider)_authenticationStateProvider).GetToken();
|
|
}
|
|
} |