2

I created Web API to receive daily temperature from OpenWeatherAPI.

Now I want to display everything on my MVC web page. I put the API call in the MVC project; plan to create new project later for better microservice architecture.

I am seeing these errors in Debug windows and MVC html with following. How do I get weather, temperature, etc, precipitation, to display on 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 Page:

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 Controller:

[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; }
}

This works in my project: 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

3
  • Don't new up your API controller in this controller. Use HttpClient to make a request to the endpoint exposed by your API controller. Commented Sep 25, 2018 at 13:57
  • hi Chris, can you submit alternative solution, thought I was already using Http client in code, thanks Commented Sep 25, 2018 at 14:46
  • You are in your actual WeatherController, but in your HomeController you're attempting to simply just call the action like a method on an instance of WeatherController. You need to use HttpClient there as well. Also, don't new up HttpClient directly. It should be treated as a singleton. See: learn.microsoft.com/en-us/aspnet/core/fundamentals/… Commented Sep 25, 2018 at 14:50

1 Answer 1

4

You're missing an await statemant when your are calling your API Action.

Your code should be like this:

ViewData["test"] =  await weathercontroller.City("Seattle");
return View();

You need to change your controller to async so it can await a method and be read by system as an async method. Your code should look like this:

public async Task<IActionResult> About()
{
    ViewData["Message"] = "Your application description page.";
    ViewData["test"] = await weathercontroller.City("Seattle");
    return View();
}
Sign up to request clarification or add additional context in comments.

3 Comments

You need to go "asyc all the way". The About action in your HomeController needs to be async: public async Task<IActionResult> About()
It's because you need to change your controller to async so it can await a method and be read by the system as an async method. Your code should look like this: public async Task<IActionResult> About() { ViewData["Message"] = "Your application description page."; ViewData["test"] = weathercontroller.City("Seattle"); return View(); }
thanks, tried it and works, gave points, thumbs up if you like question also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.