Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make HTTP calls, using ASP.NET MVC?

Tags:

c#

asp.net-mvc

What I'm trying to do:

I'm trying to practise making HTTP calls (...if that is what it's called) from a simple ASP.NET MVC web application. To do this, I am attempting to get weather details from OpenWeatherMap. You can do this by:

  • Add the following parameter to the GET request: APPID=APIKEY
    • Example: api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=1111111111

My understanding, from my learning:

  • The controller is the one to make the above HTTP call.

My question:

  • How do I actually make that HTTP GET request, in ASP.NET MVC?
like image 275
daCoda Avatar asked Dec 19 '22 05:12

daCoda


1 Answers

Use System.Net.Http.HttpClient.

You can do some basic reading from a website using something like the following:

using (var client = new HttpClient())
{
    var uri = new Uri("http://www.google.com/");

    var response = await client.GetAsync(uri);

    string textResult = await response.Content.ReadAsStringAsync();
}

You may want to make sure to test response.IsSuccessStatusCode (checks for an HTTP 200 result) to make sure the result is what you expect before you parse it.

like image 126
Erik Avatar answered Dec 21 '22 23:12

Erik