【发布时间】:2019-01-22 21:12:27
【问题描述】:
我正在尝试从 asp.net WebAPI 调用 openWeatherApi。当我从前端收到一个城市的名称时,我用它从数据库中查找城市/机场。然后,我使用机场的经纬度来调用 openweather API。我想使用响应进行进一步的计算和预测。
我的代码是:
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}");
}
运行此应用时,有时会收到 400BadRequest,有时会收到 500:Internal Server Error
1) 没有这样的主机是已知的。 2) System.InvalidOperationException:该实例已经启动了一个或多个请求。只能在发送第一个请求之前修改属性。
Startup.cs
services.AddTransient<HttpClient>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
当我尝试将完整的 openweather url 放入浏览器时,它会返回 json,但在尝试从 ASP.NET CORE Web Api 控制器运行时会出错。
任何帮助将不胜感激。
提前致谢
【问题讨论】:
标签: asp.net-mvc asp.net-core asp.net-core-webapi dotnet-httpclient