コード例 #1
0
ファイル: WeatherState.cs プロジェクト: senj/SharpMirror
        public async Task <OneCallWeatherForecast> GetWeatherForecastAsync()
        {
            OneCallWeatherForecast forecast = await _weatherForecastService.GetOneCallForecastAsync();

            WeatherForecast = forecast;
            RaiseOnChangeEvent();

            return(forecast);
        }
コード例 #2
0
        public async Task <OneCallWeatherForecast> GetOneCallForecastAsync()
        {
            if (_cache.TryGetValue("weather", out OneCallWeatherForecast currentWeather))
            {
                _logger.LogInformation("[CACHE] Got weather forecast from cache");
                return(currentWeather);
            }

            // icons: https://openweathermap.org/weather-conditions
            string apiCall = $"https://api.openweathermap.org/data/2.5/onecall" +
                             $"?lat={_configuration.Lat}" +
                             $"&lon={_configuration.Lon}" +
                             $"&appid={_configuration.ApiKey}" +
                             $"&units={_configuration.Unit}" +
                             $"&lang={_configuration.Language}";

            HttpResponseMessage response = await _httpClient.GetAsync(apiCall);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogError("Error getting weather forecast: {statusCode}", response.StatusCode);
                return(new OneCallWeatherForecast());
            }

            string responseObj = await response.Content.ReadAsStringAsync();

            JsonSerializerOptions options = new JsonSerializerOptions()
            {
                PropertyNameCaseInsensitive = true
            };
            OneCallWeatherForecast oneCallWeatherForecast = JsonSerializer.Deserialize <OneCallWeatherForecast>(responseObj, options);

            if (oneCallWeatherForecast?.Current == null)
            {
                _logger.LogError("Error getting weather forecast, response is null");
                return(new OneCallWeatherForecast());
            }

            _cache.Set("weather", oneCallWeatherForecast, new DistributedCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(60)
            });

            _logger.LogInformation("Got weather forecast");
            return(oneCallWeatherForecast);
        }