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

你好,我有一个我无法解决的问题。我无法调整我的代码以防止它在以下级别崩溃:

等待客户端.GetStringAsync (url);

哪个有一个不修改的解决方案: async void GetLieu (string place)) ?

我接受任何信息。先感谢您。

4

1 回答 1

0

参考您的最后评论:

试试这个代码:

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

怎么称呼它(例子)?!

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

结果:

结果

于 2020-12-12T22:45:03.597 回答