await client.GetStringAsync(url) ERREUR

597 Views Asked by At
 async void GetLieu(string place)
           {

            ShowProgressDialogue("Récupération des données...");

            string MonURL = "https://hubeau.eaufrance.fr/api/v1/hydrometrie/referentiel/stations";
            string url = MonURL + "?code_departement=" + place;
           
            var handler = new HttpClientHandler();
            HttpClient client = new HttpClient(handler);
            string result = await client.GetStringAsync(url);

            Console.WriteLine(result);
            var resultObjet = JObject.Parse(result);

hello, I have a problem that I can't solve. I can't adapt my code to prevent it crashing at the level of :

await client.GetStringAsync (url);

which would have a solution without modifying : async void GetLieu (string place)) ?

I am taker of any information. thank you in advance.

1

There are 1 best solutions below

7
On BEST ANSWER

Reference your last comment:

Try this code:

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace StackOverflowWebClientQuestionAnswer
{
    public class ExternalService
    {
        public async Task<string> DownloadHomepage(string place)
        {
            string MonURL = "https://hubeau.eaufrance.fr/api/v1/hydrometrie/referentiel/stations";
            string url = MonURL + "?code_departement=" + place;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) " +
                                                    "AppleWebKit/537.36 (KHTML, like Gecko) " +
                                                    "Chrome/58.0.3029.110 Safari/537.36");

                var resultat = await httpClient.GetStringAsync(new Uri(url));

                return resultat;
            }
        }
    }
}

how to call it (example)?!

using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace StackOverflowWebClientQuestionAnswer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class Resultat : ControllerBase
    {
        [HttpGet]
        public async Task<IActionResult> GetResultat()
        {
            ExternalService external = new ExternalService();

            string resultat = await external.DownloadHomepage("971");

            return Ok(resultat);
        }
    }
}

Results:

Result