public WeatherForecastResponse GetWeatherForecastData(int zipCode, string cityName) { var apikey = Environment.GetEnvironmentVariable("OPENWEATHER_APIKEY"); var client = new HttpClient(); var queryParam = String.IsNullOrEmpty(cityName)? $"zip={zipCode}":$"q={cityName}"; var resp = client.GetAsync( $"https://api.openweathermap.org/data/2.5/forecast?{queryParam},de&appid={apikey}") .Result; if (resp.StatusCode == HttpStatusCode.OK) { return(WeatherForecastResponse.FromJson(resp.Content.ReadAsStringAsync().Result)); } var errorResponse = WeatherForecastErrorResponse.FromJson(resp.Content.ReadAsStringAsync().Result); return(new WeatherForecastResponse() { StatusCode = errorResponse.StatusCode, Message = errorResponse.Message }); }
public async Task <IActionResult> Index() { // Make an API GET Call to the following URL: // http://www.7timer.info/bin/api.pl?lon=-76.8867&lat=40.2731&product=civillight&output=json try { var queryStringParams = new Dictionary <string, string>() { { "lon", "-76.8867" }, { "lat", "40.2731" }, { "product", "civillight" }, { "output", "json" } }; var pathAndQuerystring = QueryHelpers.AddQueryString("/bin/api.pl", queryStringParams); var httpResponseMessage = await client.GetAsync(pathAndQuerystring); if (httpResponseMessage.IsSuccessStatusCode) { var jsonResult = await httpResponseMessage.Content.ReadAsStringAsync(); return(View(WeatherForecastResponse.FromJson(jsonResult))); } else { return(View("Error", new ErrorViewModel() { ErrorMessage = "API call failed. Please try again later." })); } } catch (Exception ex) { //TODO: log ex.Message return(View("Error", new ErrorViewModel() { ErrorMessage = "An unexpected error occurred. Please try again later." })); } }