在 MVC 程序中调用 Web API
Call Web API within MVC Program
我创建了 Web API 以从 OpenWeatherAPI 接收每日温度。
现在我想在我的 MVC 网页上显示所有内容。我把 API 调用放在 MVC 项目中;计划稍后创建新项目以获得更好的微服务架构。
我在 Debug windows 和 MVC html 中看到这些错误,如下所示。如何获取天气、温度等、降水量以显示在 html 上。
Debug: weathercontroller.City("Seattle") The function evaluation requires all threads to run. System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>"
HTML: System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[Microsoft.AspNetCore.Mvc.IActionResult,WeatherChecker.Controllers.WeatherController+<City>d__0]"
MVC 页面:
namespace WeatherPage.Controllers
{
public class HomeController : Controller
{
public WeatherController weathercontroller = new WeatherController();
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
ViewData["test"] = weathercontroller.City("Seattle");
return View();
}
API 控制器:
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
[HttpGet("[action]/{city}")]
public async Task<IActionResult> City(string city)
{
Rootobject rawWeather = new Rootobject();
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=APIkey&units=metric");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
rawWeather = JsonConvert.DeserializeObject<Rootobject>(stringResult);
return Ok(rawWeather);
}
catch (HttpRequestException httpRequestException)
{
return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
}
}
}
public class Rootobject
{
public Coord coord { get; set; }
public Weather[] weather { get; set; }
public string _base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
这适用于我的项目:
https://localhost:55555/api/weather/city/washington
Retrieve Data From Third party Openweather Api
Should We Call Web Api from Mvc Application in Same Solution
您在调用 API 操作时缺少等待语句。
你的代码应该是这样的:
ViewData["test"] = await weathercontroller.City("Seattle");
return View();
您需要将控制器更改为异步,以便它可以等待一个方法并被系统作为异步方法读取。您的代码应如下所示:
public async Task<IActionResult> About()
{
ViewData["Message"] = "Your application description page.";
ViewData["test"] = await weathercontroller.City("Seattle");
return View();
}
我创建了 Web API 以从 OpenWeatherAPI 接收每日温度。
现在我想在我的 MVC 网页上显示所有内容。我把 API 调用放在 MVC 项目中;计划稍后创建新项目以获得更好的微服务架构。
我在 Debug windows 和 MVC html 中看到这些错误,如下所示。如何获取天气、温度等、降水量以显示在 html 上。
Debug: weathercontroller.City("Seattle") The function evaluation requires all threads to run. System.Threading.Tasks.Task<Microsoft.AspNetCore.Mvc.IActionResult>"
HTML: System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[Microsoft.AspNetCore.Mvc.IActionResult,WeatherChecker.Controllers.WeatherController+<City>d__0]"
MVC 页面:
namespace WeatherPage.Controllers
{
public class HomeController : Controller
{
public WeatherController weathercontroller = new WeatherController();
public IActionResult Index()
{
return View();
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
ViewData["test"] = weathercontroller.City("Seattle");
return View();
}
API 控制器:
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
[HttpGet("[action]/{city}")]
public async Task<IActionResult> City(string city)
{
Rootobject rawWeather = new Rootobject();
using (var client = new HttpClient())
{
try
{
client.BaseAddress = new Uri("http://api.openweathermap.org");
var response = await client.GetAsync($"/data/2.5/weather?q={city}&appid=APIkey&units=metric");
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
rawWeather = JsonConvert.DeserializeObject<Rootobject>(stringResult);
return Ok(rawWeather);
}
catch (HttpRequestException httpRequestException)
{
return BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}");
}
}
}
public class Rootobject
{
public Coord coord { get; set; }
public Weather[] weather { get; set; }
public string _base { get; set; }
public Main main { get; set; }
public int visibility { get; set; }
public Wind wind { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
这适用于我的项目: https://localhost:55555/api/weather/city/washington
Retrieve Data From Third party Openweather Api
Should We Call Web Api from Mvc Application in Same Solution
您在调用 API 操作时缺少等待语句。
你的代码应该是这样的:
ViewData["test"] = await weathercontroller.City("Seattle");
return View();
您需要将控制器更改为异步,以便它可以等待一个方法并被系统作为异步方法读取。您的代码应如下所示:
public async Task<IActionResult> About()
{
ViewData["Message"] = "Your application description page.";
ViewData["test"] = await weathercontroller.City("Seattle");
return View();
}