示例#1
0
        /// <summary>
        /// Gets the current weather forecast for a given City.
        /// </summary>
        /// <param name="city">Mandatory. City to get the current weather for.</param>
        public async Task <string> GetWeather(City city)
        {
            string requestUri = $"{_weatherBaseUrl}{city.Name},{city.Country}&appid={_weatherApiKey}";

            HttpClient client = new HttpClient {
                BaseAddress = new Uri(requestUri)
            };

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync(requestUri);

            if (response.IsSuccessStatusCode)
            {
                string responseJsonString = await response.Content.ReadAsStringAsync();

                JObject parsedJsonReponseString = JObject.Parse(responseJsonString);

                JToken weatherDescriptionJsonResult = parsedJsonReponseString["weather"].FirstOrDefault();
                JToken weatherTemperturesJsonResult = parsedJsonReponseString["main"].Last().Parent;

                if (weatherDescriptionJsonResult != null && weatherTemperturesJsonResult != null)
                {
                    WeatherDescriptionDto weatherDescriptionResult =
                        weatherDescriptionJsonResult.ToObject <WeatherDescriptionDto>();

                    WeatherTemperatureDto weatherTemperatureResult =
                        weatherTemperturesJsonResult.ToObject <WeatherTemperatureDto>();

                    WeatherHelper weatherHelper       = new WeatherHelper();
                    double        convertedTemperture =
                        weatherHelper.ConvertTemperture(weatherTemperatureResult.temp, Temperature.Celsius);

                    var mappedConitionReponse = await _weatherConditionResponseReader
                                                .GetResponseByCondition(weatherDescriptionResult.description);

                    if (mappedConitionReponse != null)
                    {
                        return($"{convertedTemperture}{Temperature.Celsius.DisplayName()} " +
                               $"with {mappedConitionReponse.MappedConditionResponse}");
                    }
                }
            }

            return(null);
        }