4

Using a class library to get data from a web API and referencing it in a MVC project within the same solution.

Keep getting an error while loading the index page in the browser saying I need to mark a Page with <%@ Page Async="true" %> or return a TASK. But the controller method will not allow me to use public async Task MakeCall(string url) saying type or namespace Task cannot be found.

Library class:

public class GetObject
{
    public async Task GetRequest(string url)
    {
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(url))
        using (HttpContent content = response.Content)
        {
            string data = await content.ReadAsStringAsync();
            HttpContentHeaders headers = content.Headers;
        }
    }
}

In the controller I use:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        MakeCall("http://api.openweathermap.org/data/2.5/weather?q=London&APPID=[APIKEY]");
        return View();
    }

    public async void MakeCall(string url)
    {
        GetObject newCall = new GetObject();
        await newCall.GetRequest(url);
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
anaximander
  • 357
  • 1
  • 5
  • 12
  • Never ever return void from an async method https://stackoverflow.com/questions/12144077/async-await-when-to-return-a-task-vs-void return Task. – Frode Nilsen Jul 25 '18 at 12:34

1 Answers1

3

Avoid async void fire and forget methods. Make the code async all the way through making sure to include the necessary namespaces like using System.Threading.Tasks;

For example

//...other using
using System.Threading.Tasks;

public class HomeController : Controller {
    public async Task<ActionResult> Index() {
        await MakeCall("http://api.openweathermap.org/data/2.5/weather?q=London&APPID=[APIKEY]");
        return View();
    }

    public async Task MakeCall(string url) {
        GetObject newCall = new GetObject();
        await newCall.GetRequest(url);

    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472