37 lines
1.1 KiB
C#
37 lines
1.1 KiB
C#
|
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);
|
|||
|
}
|
|||
|
}
|
|||
|
}
|