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);
    }
}
1

1 Answer 1

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);

    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.