WeatherDashboard/WeatherDashboard.Web/Services/WeatherApiForecastService.cs

37 lines
1.1 KiB
C#
Raw Normal View History

2023-02-10 03:33:02 +00:00
using Newtonsoft.Json;
namespace WeatherDashboard.Web.Services
{
public class WeatherApiForecastService : IForecastService
{
private readonly IConfiguration configuration;
private readonly string? apiBaseUrl;
private readonly string? apiKey;
private readonly HttpClient httpClient;
public WeatherApiForecastService(IConfiguration configuration, IHttpClientFactory httpClientFactory)
{
this.configuration = configuration;
apiBaseUrl = configuration["ApiBaseUrl"];
apiKey = configuration["ApiKey"];
httpClient = httpClientFactory.CreateClient();
}
public Task<WeatherSet> GetWeatherAsync() => InvokeRequestAsync<WeatherSet>("v1/forecast.json");
private async Task<T> InvokeRequestAsync<T>(string method)
{
var url = new UriBuilder(apiBaseUrl);
url.Path = method;
url.Query = $"key={apiKey}&q=21144";
var response = await httpClient.GetStringAsync(url.ToString());
return JsonConvert.DeserializeObject<T>(response);
}
}
}