I am trying to call the openWeatherApi from asp.net WebAPI. When I receive the name of a city from front-end, I use that to lookup the city/airport from the database. Then, I use the lat and long of the airport to call the openweather API. I want to use the response to make further calculations and predictions.
My code is:
HttpClient client = new HttpClient();
try
{
client.BaseAddress = new Uri("http://api.openweather.org");
var response = await client.GetAsync($"/data/2.5/weather?lat={airport.AirportLatitude}&lon={airport.AirportLongitude}&appid={apiKey}");
// var response = await // client.GetAsync($"/data/2.5/weather?q=London,uk&appid={apiKey}");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawWeather = JsonConvert.DeserializeObject<OpenWeatherResponse>(stringResult);
System.Console.WriteLine("$$$$$$$$$$$After API call made$$$$$$$$$$$$$$$");
System.Console.WriteLine(response);
return Ok(new {
Temp = rawWeather.Main.Temp,
Summary = string.Join(",", rawWeather.Weather.Select(x=>x.Main)),
City = rawWeather.Name
});
// return Ok(response);
}
catch(HttpRequestException httpRequestException)
{
System.Console.WriteLine(httpRequestException.Message);
return BadRequest($"Error getting weather : {httpRequestException.Message}");
}
When I run this app, sometimes I get 400BadRequest, and other times I get 500:Internal Server Error
1) No such host is known. 2) System.InvalidOperationException: This instance has already started one or more requests. Properties can only be modified before sending the first request.
Startup.cs
services.AddTransient<HttpClient>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
When I try to put the complete openweather url in my browser, it returns json, but it gives error when trying to run from ASP.NET CORE Web Api Controller.
Any help would be greatly appreciated.
Thanks in advance
You should use the using
statement
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://api.openweather.org");
var response = await client.GetAsync($"/data/2.5/weather?lat={airport.AirportLatitude}&lon={airport.AirportLongitude}&appid={apiKey}");
// var response = await // client.GetAsync($"/data/2.5/weather?q=London,uk&appid={apiKey}");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
var rawWeather = JsonConvert.DeserializeObject<OpenWeatherResponse>(stringResult);
System.Console.WriteLine("$$$$$$$$$$$After API call made$$$$$$$$$$$$$$$");
System.Console.WriteLine(response);
return Ok(new {
Temp = rawWeather.Main.Temp,
Summary = string.Join(",", rawWeather.Weather.Select(x=>x.Main)),
City = rawWeather.Name
});
// return Ok(response);
}
catch(HttpRequestException httpRequestException)
{
System.Console.WriteLine(httpRequestException.Message);
return BadRequest($"Error getting weather : {httpRequestException.Message}");
}
}