Преобразовать Get из API в асинхронный - PullRequest
0 голосов
/ 27 февраля 2020

Я пытаюсь преобразовать свое действие, чтобы все пользователи обращались к asyn c, но когда я бегу, покажите мне, например, 2 пользователя, но без имени, адрес электронной почты и т. Д. c. Я знаю, что эти поля существуют, потому что я вижу их в «show», «edit» и «delete».

Это мой код:

public IActionResult Index()
{
    IEnumerable<User> users = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://localhost:5000/api/");
        //HTTP GET
        var responseTask = client.GetAsync("users/");
        responseTask.Wait();

        var result = responseTask.Result;
        if (result.IsSuccessStatusCode)
        {
            var readTask = result.Content.ReadAsAsync<IList<User>>();
            readTask.Wait();

            users = readTask.Result;
        }
        else //web api sent error response 
        {
            //log response status here..

            users = Enumerable.Empty<User>();

            ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
        }
    }
return View(users);
}

То, что я пытаюсь преобразовать в асин c:

public async Task<IActionResult> Index()
{
    IEnumerable<User> users = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://localhost:5000/api/");
        //HTTP GET
        var response = await client.GetAsync("users/");


        if (response.IsSuccessStatusCode)
        {
            var resulString = await response.Content.ReadAsStreamAsync();
            users = await JsonSerializer.DeserializeAsync<IEnumerable<User>>(resulString);
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
        }
    }
    return View(users);
}

1 Ответ

3 голосов
/ 27 февраля 2020

Вы должны вызвать ReadAsStringAsyn c вместо ReadAsStreamAsyn c

var resulString = await response.Content.ReadAsStringAsync();
users = Newtonsoft.Json.JsonConvert.DeserializeObject<IEnumerable<User>>(resulString);
...