WeatherDashboard/WeatherDashboard.Web/Services/WeatherApiForecastService.cs

39 lines
1.3 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;
2023-03-18 15:38:35 +00:00
apiBaseUrl = configuration["Api:BaseUrl"];
apiKey = configuration["Api:Key"];
2023-02-10 03:33:02 +00:00
httpClient = httpClientFactory.CreateClient();
}
public Task<WeatherSet> GetWeatherAsync() => InvokeRequestAsync<WeatherSet>("v1/forecast.json");
private async Task<T> InvokeRequestAsync<T>(string method)
{
// sample URL
// https://api.weatherapi.com/v1/forecast.json?key=829fbbe5beb2424aa1021928230702&q=21144&days=2&aqi=no&alerts=yes
2023-02-10 03:33:02 +00:00
var url = new UriBuilder(apiBaseUrl);
url.Path = method;
2023-02-23 15:44:52 +00:00
url.Query = $"key={apiKey}&days=10&q=21144";
2023-02-10 03:33:02 +00:00
var response = await httpClient.GetStringAsync(url.ToString());
return JsonConvert.DeserializeObject<T>(response);
}
}
}