首页 > 解决方案 > 如何从 Xamarin 中的 WebAPI 获取结果值

问题描述

public async Task<Customer> GetCustomersAsync(string id)
    {
        var prod = new Customer();
        HttpClient client = new HttpClient();
        string url = "https://xxxxxx.com/api/Customers/" + id;
        client.BaseAddress = new Uri(url);
        HttpResponseMessage response = await client.GetAsync("");
        if (response.IsSuccessStatusCode)
        {
            string content = response.Content.ReadAsStringAsync().Result;
            prod = JsonConvert.DeserializeObject<Customer>(content);
        }
        return await Task.FromResult(prod);
    }

我确实调用了 API 以获取结果。但是当我无法得到返回结果时.Result

我就是这样做的:

var infocustomer = customerRepository.GetCustomersAsync(userrating);
string nameus = infocustomer.Result.NameUs;

标签: xamarinasp.net-core-webapi

解决方案


而不是这个

string content = response.Content.ReadAsStringAsync().Result;

做这个

string content = await response.Content.ReadAsStringAsync();

然后就

return prod;

推荐阅读